java 如何从服务器向客户端发送消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32113376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:41:09  来源:igfitidea点击:

How to send message from server to client

java

提问by tinaw25

I am trying to make an chatprogram in Java, when I send message on the client side the server side gets the message. But when I send from the server side to the client it do not get the message.

我正在尝试用 Java 制作一个聊天程序,当我在客户端发送消息时,服务器端会收到消息。但是当我从服务器端发送到客户端时,它没有收到消息。

I cannot see what I am doing wrong.

我看不出我做错了什么。

The server side code:

服务器端代码:

private void serverStart(){
    textArea.append("Starting server " + " \n");

    try {
        serverSocket = new ServerSocket(4444);
        textArea.append("Waiting for Clients " + " \n");

        //Reading message from the client
        socket = serverSocket.accept();

        textArea.append("Client Connected " + "\n");

        //Send message to client 
        out = new PrintWriter(socket.getOutputStream());
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (true)
        {        

            messageFromClient = in.readLine();
            whileChat(messageFromClient); 
        }
    } catch(IOException ioExecption) {
        ioExecption.printStackTrace();
    }
}

private void whileChat(String messageFromClient) {
    showMessage(messageFromClient);
    System.out.println("Message from client : " + messageFromClient);
}

protected static void showMessage(final String message) {
    SwingUtilities.invokeLater( 
    new Runnable(){
        public void run()
        {
            Gui.consoleTextArea.append(message + "\n");
        }
    });
}

public static void sendMessage(String message) {
    out.println(message);
    showMessage(name +  " : " + message + "\n");
}

The Client side :

客户端:

private void connectToServer() {

    try {
        socket = new Socket("localhost", 4444);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Thread clientThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // attach to socket's output stream with auto flush turned on
                //Send message to the server
                out = new PrintWriter(socket.getOutputStream(),
                        true);

                //Get return message from server
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                messageFromServer = in.readLine();
                whileChatting(messageFromServer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    clientThread.start();
}

private void whileChatting(String messageFromServer) {
    showMessage(messageFromServer);
    System.out.println("Message from server to client " + messageFromServer);
}

public static void Send(String msg) {
    out.println(name + " : " + msg);
    showMessage(name +  " : " + msg + "\n");
}
protected static void showMessage(final String message) {
    SwingUtilities.invokeLater( 
    new Runnable(){
        public void run(){
            Gui.consoleTextArea.append(message);
        }
    });
}

Hope someone could help me with this problem.

希望有人能帮我解决这个问题。

采纳答案by Little Santi

You could perform a flush on the PrintWriter immediately after each println, or even better: Instance the PrintWriter with autoFlush=true:

您可以在每次 println 之后立即对 PrintWriter 执行刷新,或者甚至更好:使用 autoFlush=true 实例化 PrintWriter:

out = new PrintWriter(socket.getOutputStream(), true);

In this way, each time you call println, printf, or format, the PrintWriter will perform a flush of the buffer at the end.

这样,每次调用printlnprintf、 或 时format, PrintWriter 都会在最后执行缓冲区刷新。

回答by chengpohi

 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

This line is always waiting the client output, and your client also doesn't send message to server.

此行始终在等待客户端output,您的客户端也不会向 发送消息server

Attention: both your serverand clientnot read user input.

注意:您serverclient不读取用户输入。