我建了一个简单的UDP传输,在Client端加入一个键盘监听,发现在监听完以后我的程序就不执行下一步操作了,源代码是这样的:
public class ChatClient extends Frame{
TextField t1;
TextArea t2 ;
String in = null;
boolean flag = false;
ChatClient() {
this.setBounds(200, 200, 500, 500);
this.setVisible(true);
this.setResizable(true);
this.setLayout(new BorderLayout ());
t1 = new TextField(10);
t2 = new TextArea();
t1.addActionListener(new keyEvets() );
this.add(t1,BorderLayout.SOUTH);
this.add(t2,BorderLayout.CENTER);
pack();
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String arg[]) throws Exception {
ChatClient chatclient = new ChatClient();
while(true) {
if(chatclient.flag ==false) {
continue;
}
else{
//Thread.sleep(500);
ByteArrayOutputStream a = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(a);
dos.writeUTF(chatclient.in);
chatclient.flag =false;
byte[] buf = new byte[1024];
buf = a.toByteArray();
DatagramPacket ps = new DatagramPacket(buf,0,buf.length,new InetSocketAddress("127.0.0.1",6666));
DatagramSocket ds = new DatagramSocket(4444);
dos.flush();
ds.send(ps);
System.out.println("send");
ds.close();
}
}
}
class keyEvets implements ActionListener {
public void actionPerformed(ActionEvent e) {
flag =true;
String k = t1.getText();
in = k;
t2.setText("Client:"+k);
t1.setText("");
System.out.println("key");
}
}
}
在一开始while语句里面flag为false,然后键盘输入了就为true,这些我都测试,没有错,但是发现程序就是不能执行else语句了,本来flag为true的时候是要执行的呀,而且我把它放在while(true)里面了,应该不断循环的,为什么单步测试的没有错,可是一旦正常执行就错了,求大神们指教,谢谢!
------解决思路----------------------
ChatClient发送数据时机有问题,自己优化吧。
简单修改
1.ChatClient的main方法
while (true) {
synchronized (chatclient) {
if..
else..
}
}
2.keyEvets的actionPerformed方法
synchronized (ChatClient.this) {
flag = true;
..
}