クライアントがサーバーと通信できる小さな 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();
}
}