1

这是我正在使用的代码(不是我的)

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class SimpleChatClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;

public void go() {
    JFrame frame = new JFrame("Ludicrously Simple Chat Client");
    JPanel mainPanel = new JPanel();
    incoming = new JTextArea(15, 50);
    incoming.setLineWrap(true);
    incoming.setWrapStyleWord(true);
    incoming.setEditable(false);
    JScrollPane qScroller = new JScrollPane(incoming);
    qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    outgoing = new JTextField(20);
    JButton sendButton = new JButton("Send");
    sendButton.addActionListener(new SendButtonListener());
    mainPanel.add(qScroller);
    mainPanel.add(outgoing);
    mainPanel.add(sendButton);
    frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
    setUpNetworking();

    Thread readerThread = new Thread(new IncomingReader());
    readerThread.start();

    frame.setSize(650, 500);
    frame.setVisible(true);

}

private void setUpNetworking() {
    try {
        sock = new Socket("127.0.0.1", 5000);
        InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
        reader = new BufferedReader(streamReader);
        writer = new PrintWriter(sock.getOutputStream());
        System.out.println("networking established");
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }
}

public class SendButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
        try {
            writer.println(outgoing.getText());
            writer.flush();

        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        outgoing.setText("");
        outgoing.requestFocus();
    }
}

public static void main(String[] args) {
    new SimpleChatClient().go();
}

class IncomingReader implements Runnable {
    public void run() {
        String message;
        try {
            while ((message = reader.readLine()) != null) {
                System.out.println("client read " + message);
                incoming.append(message + "\n");
            }
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
}

}

我的问题是在传入的阅读器类中为什么这一行----while ((message = reader.readLine()) != null) 从不返回null?假设线程去检查了这一行,而另一边没有给客户端的消息,那么上面的行不应该返回null吗?

谁能解释一下发生了什么?我确实知道套接字连接,我只想知道收到传入消息的情况。

4

1 回答 1

1

您正在使用诸如 BufferedReader.readLine() 之类的阻塞函数。这将阻塞,直到有东西要读。它不会“检查设备并在没有返回任何内容时返回 null”。

您可以使用 BufferedReader.available() 检查是否有任何传入数据,如果结果大于 0,则调用 readLine()。

于 2012-08-13T08:58:53.123 回答