gpt4 book ai didi

java - 套接字 catch 子句中的系统输出/错误流仅在 Debug模式下工作

转载 作者:行者123 更新时间:2023-12-01 14:34:41 25 4
gpt4 key购买 nike

就像主题中一样 - 系统输出和错误流似乎在内核类“更新”方法的 catch 子句中“卡住”。奇怪的是,当我调试项目并停在 System.out 行时,我什至可以删除突破并且一切正常。

除了最后一个 System.out 之外的所有内容都被执行,即使我替换默认的 System.out,它也不起作用。

目前,我在连接建立后立即断开用户连接。

我的代码,StartServer.java:

public class StartServer {    public static void main (String[] args) {        Kernel kernel = new Kernel(4444);        kernel.run();        while (true) {            kernel.update();        }    }}

Kernel.java:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Kernel {

ArrayList<Socket> clients;
ServerSocket socket;

public Kernel(int port) {
try {
socket = new ServerSocket(port);
clients = new ArrayList<>();
System.out.println("Server initialized");
} catch (IOException ex) {
Logger.getLogger(StartServer.class.getName()).log(Level.SEVERE, null, ex);
}
}

public void run() {
Thread thread = new Thread(){
public void run() {
try {
while (true) {
Socket client = socket.accept();
clients.add(client);
System.out.println("New user on the server!");
}
} catch (IOException ex) {
Logger.getLogger(Kernel.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
thread.start();
}

public void update() {
for (int i=0; i<clients.size(); i++) {
Socket s = clients.get(i);
try {
/*String result;
if (s.getInputStream().available()!=0) {
byte[] byteRes = new byte[s.getInputStream().available()];
char[] charRes = new char[s.getInputStream().available()];
s.getInputStream().read(byteRes);
for (int i2=0; i2<charRes.length; i2++) {
charRes[i2] = (char) byteRes[i2];
}
result = String.copyValueOf(charRes);
System.out.println(result);
}*/
throw new IOException();
} catch (IOException ex) {
try {
System.out.println("Client disconnected"); //working only in debug mode
clients.remove(s);
s.close();
i--;
} catch (IOException ex1) {
Logger.getLogger(Kernel.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}

}

最佳答案

如下更改 StartServer 类中的无限循环:

while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
kernel.update();
}

关于java - 套接字 catch 子句中的系统输出/错误流仅在 Debug模式下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16590434/

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