java计时器和套接字问题 [英] java timer and socket problem

查看:110
本文介绍了java计时器和套接字问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用套接字编程和计时器来创建一个监听客户端输入流的程序

I'm trying to make a program which listens to the client input stream by using socket programming and timer

但只要计时器执行..
it被绞死

but whenever timer executes.. it gets hanged

请帮帮我

这里是代码......

here is the code...

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    try

    {
        ServerUserName=jTextField1.getText();
        ss=new ServerSocket(5000);
        jButton1.enable(false);
        jTextArea1.enable(true);
        jTextField2.enable(true);
        Timer t=new Timer(2000, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try
                {
                    s=ss.accept();                    
                    InputStream is=s.getInputStream();
                    DataInputStream dis=new DataInputStream(is);
                    jTextArea1.append(dis.readUTF());

                }
                catch(IOException IOE)
                {
                }
                catch(Exception ex)
                {
                    setLbl(ex.getMessage());
                }

            }
        });
        t.start();
    }
    catch(IOException IOE)
    {

    }
}

提前致谢

推荐答案

使程序多线程化;一个线程侦听套接字,另一个线程处理GUI。使用SwingUtilities.invokeLater让GUI线程(事件调度线程)在网络线程接收数据时进行GUI更新。

Make the program multi-threaded; one thread listens on the socket, the other one handles the GUI. Use SwingUtilities.invokeLater to let the GUI thread ("event dispatching thread") do the GUI updates whenever the network thread receives data.

这篇关于java计时器和套接字问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆