【发布时间】:2014-11-01 23:27:39
【问题描述】:
每当单击 GUI 窗口上的按钮并且服务器接收到消息并将其发送到连接到同一端口的另一个客户端客户端 2 时,我都会通过客户端 1 向服务器发送一条字符串消息“5”作为客户端 1。当单击按钮时,客户端 2 确实收到字符串消息“5”,但问题是一旦单击按钮,客户端 1 的整个 GUI 窗口就会冻结(无法单击任何事物)。客户端 2 也是如此,它执行相同的操作,即在单击按钮时发送字符串消息“2”,但在单击按钮时 GUI 窗口也会冻结。为什么 GUI 窗口冻结?
代码sn-p:
BufferedReader buffR;
Socket sock = new Socket(nameHost, portNum);
PrintWriter printW = new PrintWriter(sock.getOutputStream());
this.buffR = new BufferedReader(new InputStreamReader(sock.getInputStream()));
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
printW.println("5");
printW.flush();
}
});
已编辑 - 附加代码片段(接收部分): 这是线程类中的一个可运行方法以及上面的代码 sn-p。
public void run() {
try{
while(true){
String line = br.readLine();
int update = Integer.parseInt(line);
current-= update; //int current = 0 and update is the number received from the other client, which is "5"
JLabel newNumber = new JLabel(current); //Assign the newNumber JLabel with the current number
jp.remove(number); //Remove the JLabel 'number' which initially shows "50"
jp.revalidate();
jp.repaint();
jp.add(newNumber); //Replace the JLabel 'number' with 'newNumber'
if(update == 0){
JOptionPane.showMessageDialog(jf, "Reached 0", "Message", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
} catch (IOException ioe){
System.out.println("ioe in ChatClient.run: " + ioe.getMessage());
}
}
【问题讨论】:
-
你认为 while (true) 循环有什么作用?什么时候停止?
-
你到底需要多少个动作监听器?
-
@JBNizet 我想让两个客户端继续通过按下按钮发送消息来相互交互,所以我把它作为一个 while 循环。我怎样才能以交互持续到终止的方式修复它?
-
@BoristheSpider 只有两个,但我怎样才能修复它,使两个客户端之间的交互持续到它们的任何一个窗口终止?
-
@user3466314:是的,您需要一个循环来从 PrintWriter 信息中获取信息,但不要不断添加 ActionListener,因为这种方式很疯狂。我从循环中的 BufferedReader 读取,然后在 GUI 中显示结果(但注意以线程安全的方式显示字符串)。我会使用 SwingWorker 来帮助我做到这一点。
标签: java multithreading swing user-interface networking