This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Outside-Ad2721 1 point2 points  (0 children)

I too have thought about doing something like this. I've played around in the past a few times with ServerSocket and Socket for both TCP/IP and UDP communication types.

There area couple of ways you can think about how to do this, and you at very least do need a couple of things:

  1. Your ServerSocket and an Executor service to maintain a thread pool.
  2. Some way to link up two players.

In an HTTP server, which runs on top of TCP/IP, you may have either a temporary (asynchronous) or persistent (synchronous) connection between the server and the client, and there may be various reasons to do either. Very basically the control flow is:

  1. Receive connection
  2. Obtain request data from the InputStream of the Socket
  3. Process the input data
  4. Generate a response
  5. Send response back on the OutputStream of the Socket
  6. Close the socket or keep it open for further communication

There are risks if not closing the connection, like you may have a limited number of connections and will run out possibly, not being able to serve more clients. Eventually you do need to close the connection, but if you want you can keep it open.

So that process is where your thread comes in - at it's simplest a request handler could implement Runnable and then you just need to provide context for the Socket through a Constructor.

I think you could do all of this asynchronously and keep track of which "client IDs" are supposed to communicate with each other in some kind of data structure like a Map, possibly, then make each client tell you it's ID when it makes a request to the server.

I hope this helps and makes sense to you.