I need help thinking up a design where clients connect and communicate with all other clients. I’m thinking each client will simultaneously need a ServerSocket for listening for incoming connections from other clients and a Socket for initiating connections with other clients.
I’m testing on localhost, so if I use ports numbers to keep track of connections, I run into this scenario:
Socket A (OS assigned port: a) initiates connection with ServerSocket B (known port: 2222)
Both clients record that connection (a, 2222) is made
Socket B (OS assigned port: b) initiates connection with ServerSocket A (known port: 1111)
Both clients record that connection (b, 1111) is made
We should have 1 connection per pair of clients, so the above is a wasteful. THAT’S why I’m thinking setting about setting local ports myself: the scenario would change to connections (1111,2222) and (2222,1111), and since the second is the same, it’s not kept.
Does this sound reasonable?
Why do you require the client to set it’s local port? The way client, server sockets work is a bit different.
Essentially when you have clients talking to each other, what you’re getting at is, every client has a incoming port (server socket) that it’ll listen on for other clients. When a client wishes to connect to a different client, it’ll always use this port to initiate the request. Upon getting the request, the client will simply accept the connection and pass it to the handling logic (be it a thread or NBIO type logic). In this scenario you don’t have to define the local port anywhere.
I think one of the issues that you’re trying to solve is, what if a connection is already established between two clients? In that case, both parties know whom are the connected to and will not establish a new connection. In which case you’re looking at implementing your own protocol for a two-way duplex communication.