チャットプログラム用のサーバーを作成しようとしていますが、何らかの理由で入力を受け取るだけで、Enterキーを何度も押してもそれを実行し続けます。コマンドラインでのみサーバーを実行しようとしているため、サーバーにいくつかのコマンドを与えることができません。なぜそれがこれをしているのか誰かが知っていますか?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class Server {
ArrayList<PrintWriter> clientOutputStreams;
int port;
ServerSocket serverSocket;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket socket;
public ClientHandler(Socket clientSocket) {
try {
socket = clientSocket;
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
tellEveryone(message);
System.out.println(message);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
new Server().go();
}
public void createSocket() {
try {
port = 31996;
serverSocket = new ServerSocket(port);
} catch (Exception e) {
System.out.println("The port is in use or does not exist! Please pick an unused port between 1025 and 65535.");
createSocket();
}
}
public void go() {
clientOutputStreams = new ArrayList<PrintWriter>();
try {
createSocket();
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Server started on port " + port+ ".");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void tellEveryone(String message) {
Iterator<PrintWriter> it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}