Java Socket Server

Exercise Your Mind

Java Socket Server

A socket server is the basis of communication for most networked applications.  I figured that this is something so basic that it’s important enough to share. The principles are pretty simple at this layer:

  1. Listen on a specified port
  2. Spawn a thread to service that connection
  3. Output data received to a log file (you can implement server responses in this phase)
  4. Listen on the same port for additional connections

I created two classes, one for main to spawn the worker, and another for the actual worker.

Here’s the main class:

You may be wondering why I even bother with threads. The reason is that the main method that accepts the incoming connection is blocking, meaning that if I didn’t use threads, then my application would appear to have locked up and it wouldn’t be able to accept other incoming connections. This way, if a new connection comes in, we can service it in it’s own thread, and wait for another connection to come in.

Here’s the worker:

 

One Response

  1. Jess says:

    I really enjoyed your four-point explanation at the top of the page. I couldn’t understand a lick of what the code meant, but I know what it does now!

Leave a Reply

Your email address will not be published. Required fields are marked *