-1
我已经实现了一个小型Java聊天室程序,客户端可以与服务器通信。尽管多个客户端无法工作 - 我相信这是因为客户端在连接时预留了套接字?有没有简单的方法来添加多个客户端功能?谢谢你的帮助。与多个客户端通信 - 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();
}
}
问题是每个连接会覆盖前一个连接。您需要有多个连接字段和多个输入/输出流。真的需要产生一个线程来处理连接,并且_it_可以维护连接和流。 – Gray 2013-02-14 19:29:07
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html - 请参阅本教程的最后一节,它有一个完整的工作示例,说明如何支持多个客户端。 – 2013-02-14 19:42:14