gpt4 book ai didi

Endless BufferReader reading(无休止的BufferReader阅读)

转载 作者:bug小助手 更新时间:2023-10-24 17:54:32 28 4
gpt4 key购买 nike



I wrote some program that has to receive and send messages. But I have some troubles with streams. I start my server and program. Then I'm trying send message, but my program just freezes. I used telnet and it works. I use sockets in this project and try do some messenger.

我写了一些程序,必须接收和发送消息。但我对溪流有一些问题。我启动我的服务器和程序。然后我试着发送消息,但我的程序就是死机了。我使用了远程登录,它起作用了。我在这个项目中使用套接字,并尝试做一些信使。


        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
button.addActionListener(e ->{
try {
out.write(textField.getText() + "\n");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
try {
textArea.append(in.readLine()+"\n");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
textArea.setCaretPosition(textArea.getText().length());
textField.setText("");
});
setVisible(true);
}

public static void main(String[] args) throws IOException {
new Main().Draw();
}
}

public class Server {
private static ArrayList<Receiver> receivers = new ArrayList<>();

public static ArrayList<Receiver> sockets(){
return receivers;
}

public static void main(String[] args) {
try(ServerSocket serverSocket = new ServerSocket(4040)){
while (true){
Socket socket = serverSocket.accept();
receivers.add(new Receiver(socket));
}
}
catch (IOException e){
e.printStackTrace();
}
}

@Override
public void run() {
String message = null;
while (true){
try {
message = in.readLine() + "\n";
} catch (IOException e) {
throw new RuntimeException(e);
}
for(Receiver socket : Server.sockets()) {
try {
socket.out.write("Your message: " + message+"\n");
socket.out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

更多回答

Please show a minimal reproducible example. The current code you showed is incomplete.

请给出一个最小的可重现的例子。您显示的当前代码不完整。

Lack of any visible threading looks suspicious.

没有任何可见的线看起来很可疑。

your problem might be caused by lack of flushing, see here: stackoverflow.com/questions/24312147/…

您的问题可能是由于缺少刷新所致,请查看此处:Stackoverflow.com/Questions/24312147/…

You are ignoring end of stream here: in.readLine(). It will return null at end of stream, at which point you should close the socket and stop reading.

您在这里忽略了流的结束:in.readLine()。它将在流的末尾返回NULL,此时您应该关闭套接字并停止读取。

You will be blocking the EDT. Almost never can you expect a GUI to work with network IO without multithreading. Look at the excellently-documented SwingWorker

你会挡住美国东部夏令时。几乎不可能指望图形用户界面在没有多线程的情况下与网络IO一起工作。看看记录精良的SwingWorker吧

优秀答案推荐
更多回答

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