我正在尝试创建一个简单的TCP客户端服务器应用程序接口 用户可以在按下相应按钮时启动或停止服务器 当用户按下应连接到服务器的按钮时,我创建了一个StartServer按钮 面临的问题是当用户点击按钮时发生注意并且界面停止
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultListModel dlm=new DefaultListModel();
String clientSentence;
String capitalizedSentence;
try {
welcomeSocket= new ServerSocket(6789);
dlm.addElement("server started..");
dlm.addElement("Server Waiting for Connections on Port 6789");
jList1.setModel(dlm);
displayfull();
while(true)
{
DataOutputStream outToClient = null;
try {
Socket connectionSocket = welcomeSocket.accept();
//dlm.addElement("Client Connected ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//dlm.addElement("Obtained a handle on Client Input Stream");
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
//dlm.addElement("Obtained a handle on Client Output Stream");
clientSentence = inFromClient.readLine();
//dlm.addElement("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
//dlm.addElement("Message Sent");
} catch (Exception e) {
}
}
} catch (Exception e) {
dlm.addElement(e);
}
jList1.setModel(dlm);
displayfull();
}
答案 0 :(得分:2)
正如其他人所暗示的那样,你正在Event Dispatch Thread上花费宝贵的时间 如果您阅读了有关如何Concurrency in Swing的教程,您会发现您获得了Swing worker等工具。
Stack Overflow上有很多这样的问题,有些问题比其他问题更有用。