所以,我检查过,就像我正在刷新我的PrintWriter(我将其设置为autoflush),服务器运行的端口与客户端连接的端口匹配,服务器先运行,这是所有都在localhost上运行,所以没有路由器/防火墙问题,但由于某些原因,这不起作用。
public class Server {
public static ArrayList<String> Username = new ArrayList<String>();
public static ArrayList<InetAddress> Address = new ArrayList<InetAddress>();
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(Integer.parseInt(args[0]));
for(;;) {
Socket client = socket.accept();
new Thread(new Runner(client)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Runner implements Runnable {
private final Socket client;
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
String info = reader.readLine();
System.out.print(info + "\n");
InetAddress address = client.getInetAddress();
System.out.print("Connected to: " + address + " & username is: " + info + "\n");
Server.Username.add(info);
Server.Address.add(address);
int i = 0;
for(String user : Server.Username) {
i++;
writer.write("[" + i + "] " + user);
System.out.print("[" + i + "] " + user + "\n");
}
writer.close();
reader.close();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Runner(Socket clientSock) {
client = clientSock;
}
}
public class Client {
private String host;
private int port;
private String user;
public Client(String hostname, String username, int portNum) {
host = hostname;
user = username;
port = portNum;
}
public void connect() {
try {
Socket socket = new Socket(host, port);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.write(user + "\n");
while(reader.readLine() != null) {
System.out.println(reader.readLine());
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client("127.0.0.1", "hshsh", 33333);
client.connect();
}
}
我尝试运行RawCap来监控localhost上的流量,但输出对我来说太过分了。我不太了解TCP enuff来读取转储,输出中似乎也有很多垃圾。握手看起来没问题,而且我非常确定客户端和服务器是否已连接。我认为我的问题在于使用PrintWriter和BufferedReader,以及我可能如何关闭资源。
关闭服务器后,我从客户端收到此消息。
Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.connect(Client.java:23)
at Client.main(Client.java:32)
我添加了一个print语句,客户端连接正常。最后一点,我在上一个程序中有一条错误消息,它是我的缓冲区的组合,不是刷新而不是关闭资源。这一次,我将PrintWriter设置为autoflush,并且我关闭了服务器端的所有资源。我还需要关闭客户端吗?