以下代码在编译时是正确的,但在运行时显示: ConnectException 错误图像:
import java.net.*;
import java.io.*;
class TcpChat
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("Ip",20000);
ServerSocket ss = new ServerSocket(20000);
new Thread(new TcpClient(s)).start();
new Thread(new TcpServer(ss)).start();
}
}
class TcpClient implements Runnable
{
Socket s;
TcpClient(Socket s)
{
this.s = s;
}
public void run()
{
try
{
OutputStream out = s.getOutputStream();
out.write("hello javaserver".getBytes());
s.close();
}
catch (Exception e)
{
}
}
}
class TcpServer implements Runnable
{
ServerSocket ss;
TcpServer(ServerSocket ss)
{
this.ss = ss;
}
public void run()
{
try
{
Socket s = ss.accept();
InputStream in = s.getInputStream();
byte[] buf =new byte[1024];
int length =in.read(buf);
String ip =s.getInetAddress().getHostAddress();
String data = new String(buf,0,length);
System.out.println(ip+":::"+data);
s.close();
ss.close();
}
catch (Exception e)
{
}
}
}
此外,我使用的 IP 地址没有错误,在我的 PC 中我使用自己的 IP。