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



就像在topic - System out和err流似乎被"冻结"在内核类的"update"方法的catch子句中。奇怪的是,当我调试项目,并停止在系统。我甚至可以删除突破,一切都正常工作。

除了最后一个系统。out被执行,它不工作,甚至当我替换默认的System.out.

此刻,我正在断开连接后刚刚建立的用户。

我的代码StartServer.java:

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

尝试添加

System.out.flush();

System.out.println()

相关内容

  • 没有找到相关文章

最新更新