可能重复:
java 计时器和套接字问题
所以这里是代码。我想要做的 - 是与服务器的客户端循环,以从服务器获取消息,有时会发送它们。这是尝试使用计时器。
private MessageFrame mf;
private User us;
private Contact cn;
private Socket s;
private PrintStream ps;
private BufferedReader br;
private Timer timer ;
public MessageFrameListener(MessageFrame m_f, User u_s, Contact c_n){
timer = new Timer(500,new timerListener());
mf = m_f;
us = u_s;
cn = c_n;
m_f.addButtonListener(new SButtonListener());
m_f.addWinListener(new FrameListener());
}
public void init(){
try {
s = new Socket(InetAddress.getLocalHost(), 8072);
ps = new PrintStream(s.getOutputStream());
br = new BufferedReader( new InputStreamReader(s.getInputStream()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.start();
}
public class timerListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//String insert = mf.getInput();
String result;
try {
//проверить, что буфер не пуст
if((result = br.readLine()) != null){
String[] results = result.split(" ");
if("m".equals(results[0])){
if("-1".equals(results[2]))
mf.addLine2("Error");
else{
mf.addLine2(results[3]);
}
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
但是当我运行它时 - 程序停止对我的行为做出反应。我不能写文字,也不能按一个按钮。