我已经实现了一个小型 Java 聊天室程序,客户端可以在其中与服务器通信。尽管多个客户端不起作用-我相信这是因为客户端在连接时保留了一个套接字?有没有一种简单的方法来添加多个客户端功能?谢谢你的帮助。
public void startRunning(){
try{
server = new ServerSocket(6789, 100); // port no, max users
while(true){
try{
waitForConnection();
setupStreams();
connectionRecieving();
}catch(EOFException eofException){
showMessage("Server ended connection \n");
}finally{
closeConnection();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
// Wait for connection
private void waitForConnection() throws IOException{
showMessage("Attempting connection... \n");
connection = server.accept();
showMessage("Connected to: " + connection.getInetAddress().getHostName() + "\n");
}
// Get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
}
// Close streams and sockets
private void closeConnection(){
showMessage("----- \nClosing connections... \n");
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}