1
我正在嘗試爲我的聊天程序創建一個服務器,但由於某種原因,它只是需要輸入,並且即使在反覆按下輸入時也會繼續這樣做。我試圖只在命令行中運行服務器,所以這使得無法給服務器一些命令。有誰知道它爲什麼這樣做?我的程序想要繼續從命令行輸入
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();
}
}
}
}