简体   繁体   English

通过套接字发送的消息未在接收方打印

[英]Messages sent over socket not being printed on the receiving side

I am currently learning Java, and I tried to make a simple chat program, which communicates between a server and a client. 我目前正在学习Java,并且尝试制作一个简单的聊天程序,该程序在服务器和客户端之间进行通信。 My problem is that the two programs connect properly to each other, but send messages do not get print out. 我的问题是两个程序可以正确地相互连接,但是发送的消息无法打印出来。 I do not know whether it is the sending or receiving part. 我不知道它是发送方还是接收方。 Do not judge my class naming, it is just temporarily. 不要判断我的班级命名,这只是暂时的。

The client-side part of receiving: 客户端部分接收:

InputStream is = chatterSock.getInputStream();
OutputStream os = chatterSock.getOutputStream();
    Thread readThread = new Thread(() -> {
    while (true) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }

            chatter.print("<p>" + out.toString() + "</p>");

        } catch (IOException ex) {
            chatter.printWarning("Connection lost");
        }

    }

The server-side part is pretty similar. 服务器端部分非常相似。

To send messages I just run 要发送消息,我只是运行

<Socket>.getOutputStream().write(<String>.getBytes());

I already tried some other posts from stackoverflow, but did not find a way that works. 我已经尝试过stackoverflow的其他一些帖子,但是没有找到一种可行的方法。 Thanks for your help! 谢谢你的帮助!

Edit: here is the server side: 编辑:这是服务器端:

InputStream is = chatterSock.getInputStream();
OutputStream os = chatterSock.getOutputStream();

Thread readThread = new Thread(() -> {
    while (true) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }
            overlord.print("<p>" + out.toString() + "</p>");

        } catch (IOException ex) {
            overlord.chatterSockList.remove(overlord.chatterSockList.indexOf(chatterSock));
            overlord.printWarning("Connection to " + chatterSock.getInetAddress() + " lost");
            overlord.sendToAll(("User " + username + " disconnected."));
        }
    }

});

Edit: The message gets send here: 编辑:消息发送到这里:

sendButton.addActionListener(e -> {

    try {
        chatterSock.getOutputStream().write((messageArea.getText()+"\n").getBytes());
        messageArea.setText("");
    } catch (IOException ex) {
        System.err.println(ex);
        printWarning("Connection lost"); //TODO heartbeat
    }
});

As @Russell Uhl mentions in his comment, a read loop whose termination condition is reader.readLine()) != null is only going to terminate when the output stream is closed. 正如@Russell Uhl在其评论中提到的那样,其终止条件为reader.readLine()) != null的读取循环仅在输出流关闭时才会终止。

If the output stream is not closed, that call simply waits for new information, and shall continue to do so indefinitely. 如果未关闭输出流,则该调用仅等待新信息,并且将无限期地继续这样做。

It is also going to wait indefinitely if you don't send over a newline, which is why you were told to add it to your write command. 如果您不发送换行符,它将无限期等待,这就是为什么要求您将其添加到write命令中的原因。

It would be best to process each line you read separately, rather than trying to append them to a buffer and output them all together. 最好分别处理您阅读的每一行,而不是尝试将它们附加到缓冲区并一起输出。 Do the processing inside the loop. 在循环内进行处理。

And probably it's also a good idea to add some button to your GUI to terminate the chat. 在GUI中添加一些按钮以终止聊天也是一个好主意。 It will disable the rest of the GUI and close the output stream, which in turn will cause the readLine() to return null, and the loop to terminate properly. 它将禁用其余的GUI并关闭输出流,这又将导致readLine()返回null,并且循环正确终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM