gpt4 book ai didi

java简单聊天客户端查询

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:55 25 4
gpt4 key购买 nike

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

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

}

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

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

最佳答案

您正在使用阻塞函数,例如 BufferedReader.readLine()。这将阻塞,直到有东西可读。它不会“检查设备,如果没有返回则返回 null”。

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

关于java简单聊天客户端查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com