所以我要创建一个聊天室,其思想是服务器和客户端是多线程的。因此,当客户端发送一条消息时,它将去往服务器,服务器将其与其余的聊天日志一起放入文件中,然后客户端每隔一段时间(在第二个线程上)就将连接到服务器(在第二个线程上)第二个线程)。服务器从那里发送文件,客户端将其放入消息框。这是一个图:
如果您遵循箭头指示,您将可以发现它。 :)无论如何,因此Thread的一部分是完美的,并且工作正常。但是,一旦一个线程结束(一旦客户端的消息在服务器文件中),第二个线程就会启动,也就是坏东西开始的时候。
马上,我从客户端收到EOFException(它没有说明在哪里),而从服务器收到BindException(我认为这是由于客户端方面的错误造成的)。
这是服务器线程2中的代码:
System.out.println("Waiting for a client...");
// Start a server
ServerSocket server = new ServerSocket(3210);
// Listen for anyone at that port
Socket socket = server.accept();
System.out.println("A client has connected!");
// Open the output stream
DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
// Get the file and convert it to a byte array
Path path = Paths.get("history.txt");
byte[] bytes = Files.readAllBytes(path);
// Send the size of the file in bytes
outputStream.writeInt(bytes.length);
// Send the file
outputStream.write(bytes);
// Close everything
socket.close();
outputStream.close();
server.close();
还有来自客户端线程2的代码:
// Start socket
Socket socket = new Socket("DESKTOP-FUR3UF6", 3210);
// Get input stream
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
// Get amount of bytes in file
int length = inputStream.readInt();
if (length > 0 && allMessagesTextBox.getText() != null) {
// Get the bytes from the file and put that out to the message box
byte[] bytes = new byte[length];
inputStream.readFully(bytes, 0, bytes.length);
String data = new String(bytes, "UTF-8");
allMessagesTextBox.setMessage(data);
}
else {
// Put this message on the message box
allMessagesTextBox.setMessage("Connecting...");
}
// Close socket and input stream
inputStream.close();
socket.close();
客户端和服务器代码都位于try / catch块中,所以您知道。
但是,我的部分问题是我不完全了解EOFException。据Oracle称,它是在输入过程中意外到达文件末尾或流末尾时发生的,但是我不明白为什么在我的代码中会发生这种情况。
有人可以启发我为什么会出错,以及如何解决吗?谢谢!!