Java socket client doesn't detect server messages

不想你离开。 提交于 2020-05-16 22:00:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!