java简单聊天客户端查询

时间:2012-08-13 08:44:14

标签: java

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

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吗?

有人可以解释一下发生了什么吗?我知道套接字连接和所有 我只是想知道收到传入消息的情况。

1 个答案:

答案 0 :(得分:1)

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

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