开发者

Listening for connections in a separate thread

This is part of a messenger project in java. Because clients use direct connections to chat, I want eavry client to listen on some port, and 开发者_如何学Goothers to make a socket to that address. but when i call ServerSocket.accept() in another thread it appears that all threads have been suspended. which means nothings happens after executing that command. Here is the code which makes new thread.

java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        while(true){
                            System.out.println("flag1");
                            Socket socket = listeningSocket.accept();
                            System.out.println("flag2");
                            new Chat(socket).setVisible(true);;
                            jTextArea1.append("successfully connected\n");
                        }
                    } catch (NullPointerException e) {
                        System.out.println("i know");
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                        jTextArea1.append("error in recieving connection\n");
                    }
                }
            });

any ideas how to solve this?


when i call ServerSocket.accept() in another thread it appears that all threads have been suspended

Appears how? accept() only blocks the current thread. Are you calling it in the AWT thread? e.g. an actionPerformed() method? Don't do any network operations in those methods, use separate threads.


Socket.accept() DOES block the CURRENT thread. You'll see "flag2" printed only after a connection is received. But it blocks only CURRENT thread.

I suspect you are not running the separate thread correctly (you're calling yourThreadHere.start(), not .run(), right?).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜