java定时器和socket问题 [英] java timer and socket problem

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

问题描述

我正在尝试使用套接字编程和计时器制作一个侦听客户端输入流的程序

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

但是每当计时器执行..挂了

but whenever timer executes.. it gets hanged

请帮帮我

这是代码...

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定时器和socket问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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