2

我正在制作服务器端应用程序,但是当我尝试将文本附加到 时JTextarea,它不起作用。但是,它会打印到控制台。

在我添加该行之前它工作正常serverSocket.accept()

这是我的代码:

try { 
    serverSocket=new ServerSocket(4545); 
    LogOutput.append("Seccessfuly connected\n" );  
    System.out.println("Seccessfuly connected\n" );              

    StartButon.setEnabled(false);

    while(true){
        LogOutput.append("waiting for client\n" );
        System.out.println("waiting for client\n" ); 

        serverSocket.accept();
        LogOutput.append("Client connected to server\n" );               
    }
}
catch(Exception e){
    LogOutput.append("cannot establish connection : "+ e +"\n" );
    StartButon.setEnabled(true);
}
4

2 回答 2

4

从给定的代码片段和您的问题看来,您正在寻找

客户端连接到服务器\n

要添加到您的 textArea。

serverSocket.accept();
LogOutput.append("Client connected to server\n" );       

一旦你说 serverSocket.accept() 现在它会等待客户端连接到达,除非有一些客户端你的下一行代码不会被执行。serverSocket.accept 是阻塞方法,启动您的客户端程序,您的服务器将开始处理下一行代码。

文档

public Socket accept() throws IOException

侦听要与此套接字建立的连接并接受它。该方法阻塞,直到建立连接。

于 2012-06-06T19:07:31.113 回答
4

You're completely blocking the Swing event thread or EDT. Get most of that code, starting with the while (true) block onto a background thread if you want your Swing GUI to function in conjunction with a long-running process. Please read the Concurrency in Swing tutorial to see why this matters, and how to solve this issue with a SwingWorker object.

于 2012-06-06T19:15:21.523 回答