问题
I am attempting to run a Java server socket on a remote host which will regularly broadcast messages (determined by external processes) to all connected clients.
The server socket is defined as:
ServerSocket serverSocket = (ServerSocket) ((ServerSocketFactory)ServerSocketFactory.getDefault()).createServerSocket(3050);
while (true) {
Socket socket = serverSocket.accept();
remoteService.addSocket(socket);
}
Which will keep track of the socket connections in an array list. The method below will then be called whenever a broadcast needs to be sent:
public void broadcastMessage(String message){
for (Socket socket : remoteService.getSockets()) {
System.out.println("Sending message: " + message);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.write(message);
}
}
On the client side, the setup is as below:
Socket socket = (Socket) ((SocketFactory) SocketFactory.getDefault()).createSocket(serverHost,portNum);
BufferedReader socketBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = socketBufferedReader.readLine();
if (message != null && message != "") {
System.out.println("Message received: " + message);
};
}
The server is correctly printing the "Sending message" string as many times as there are clients connected, but none of the client processes print anything. Any idea how to get the clients to properly listen to the socket inputstream?
回答1:
PrintWrite.println() method will print the String it's given and terminate the line. Using the below on the server side worked:
public void broadcastMessage(String message){
for (Socket socket : remoteService.getSockets()) {
System.out.println("Sending message: " + message);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(message);
}
}
来源:https://stackoverflow.com/questions/61512556/java-socket-client-doesnt-detect-server-messages