Reputation: 821
So for a project I am making a little peer to peer, two person chat client using Java in the Netbeans IDE.
My question isn't exactly code but more about structure and how to implement.
What I want to do is have the client open and have a ServerSocket
listening for any connections that are trying to be made from another client using a Socket
(This other client is also supposed have a ServerSocket
)
So the idea is that both clients have the ability to accept a connection once the client is opened and have the ability to try and make a connection.
Anyway, the issue is that ServerSocket.Accept();
blocks (Correct terminology?) the program once it is called until the time-out finishes. What I want is that the ServerSocket
just listens in the background for any incoming connections and connects them if so, without disabling the function of the program entirely(i.e. the user being able to initiate connection themselves) while this occurs?
To do this do I need to create a separate thread for the ServerSocket
, which is killed once the connection has been made?
Also, once the connection has been made, how do I get the program to periodically check the input stream of the Socket
to see if there are any incoming messages from the other client?
Is there a way I can achieve this in a single thread? (I haven't really delved into threads yet)
I'm sorry if this is a bit broad.
Thanks so much!!
Upvotes: 1
Views: 1007
Reputation: 362
ServerSocket blocks and that's it.
But if you only want peer-to-peer communication between two connected parties and nothing more then this behavior is not a problem. You just need two programs: server and client. Server block until it gets connection from client and client blocks until it gets connection.
If you want to implement Java IO in single thread you should use Java Nio. There are lots of tutorials for that in internet. For example http://tutorials.jenkov.com/java-nio/server-socket-channel.html.
Also it seems that you are not very familar with networking and sockets so it might be beneficial to use some layer instead of raw sockets.
Maybe you should consider JeroMQ (https://github.com/zeromq/jeromq) for implementing communication between programs.
Upvotes: 1