问题
I'm trying to write a simple socket server for a project of mine, but it only accepts one request and then doesn't accept anything else from anywhere.
public void run() {
println("Socket server running...");
try {
sock = new ServerSocket(20424);
while(true) {
clientSocket = sock.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data;
while((data = in.readLine()) != null) {
println("[SocketServer] " + data);
if(data.equalsIgnoreCase("COUNT(TRIGGERS)")) {
out.println(getTriggerCount());
}
}
out.println("endOfStream");
out.close();
in.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
It will accept one request and respond with the correct amount of data, but after that nothing works. Here's the client I'm using to connect:
public static void main(String[] args) {
try {
socket = new Socket("localhost", 20424);
out = new PrintWriter(socket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.println("COUNT(TRIGGERS)");
String data;
while((data = in.readLine()) != null) {
System.out.println(data);
}
socket.close();
} catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
回答1:
It will accept the next connection as soon as the inner while ends...
Maybe you want to create socket handlers for the incoming connections with their own threads, so you can handle multiple connections simulatanously.
来源:https://stackoverflow.com/questions/12771360/java-socket-server-only-accepts-one-request-then-stops-accepting