簡體   English   中英

通過套接字發送的消息未在接收方打印

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

我目前正在學習Java,並且嘗試制作一個簡單的聊天程序,該程序在服務器和客戶端之間進行通信。 我的問題是兩個程序可以正確地相互連接,但是發送的消息無法打印出來。 我不知道它是發送方還是接收方。 不要判斷我的班級命名,這只是暫時的。

客戶端部分接收:

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

    }

服務器端部分非常相似。

要發送消息,我只是運行

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

我已經嘗試過stackoverflow的其他一些帖子,但是沒有找到一種可行的方法。 謝謝你的幫助!

編輯:這是服務器端:

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

});

編輯:消息發送到這里:

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

正如@Russell Uhl在其評論中提到的那樣,其終止條件為reader.readLine()) != null的讀取循環僅在輸出流關閉時才會終止。

如果未關閉輸出流,則該調用僅等待新信息,並且將無限期地繼續這樣做。

如果您不發送換行符,它將無限期等待,這就是為什么要求您將其添加到write命令中的原因。

最好分別處理您閱讀的每一行,而不是嘗試將它們附加到緩沖區並一起輸出。 在循環內進行處理。

在GUI中添加一些按鈕以終止聊天也是一個好主意。 它將禁用其余的GUI並關閉輸出流,這又將導致readLine()返回null,並且循環正確終止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM