Java 套接字客户端未检测到服务器消息

Java socket client doesn't detect server messages

我正在尝试 运行 远程主机上的 Java 服务器套接字,它将定期向所有连接的客户端广播消息(由外部进程确定)。

服务器套接字定义为:

        ServerSocket serverSocket = (ServerSocket) ((ServerSocketFactory)ServerSocketFactory.getDefault()).createServerSocket(3050);

        while (true) {
            Socket socket = serverSocket.accept();
            remoteService.addSocket(socket);
        }

它将跟踪数组列表中的套接字连接。每当需要发送广播时,将调用以下方法:

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);
    }
}

在客户端,设置如下:

        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);
            };
        }

服务器正确打印 "Sending message" 字符串的次数与连接的客户端一样多,但是 none 的客户端进程打印任何内容。知道如何让客户端正确收听套接字输入流吗?

PrintWrite.println() 方法将打印给定的字符串并终止该行。在服务器端使用以下内容有效:

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);
    }
}