A Java socket client class (example source code)

Summary: This article shares the source code for a simple Java Socket client class. This article demonstrates both (a) how to write to a Java socket, and (b) how to read from a Java socket.

Background

I’ve been working with Java networking lately, specifically writing some Java socket client applications to communicate over networks using Java sockets. Since I put a little work into creating a simple Socket client, I thought I’d share my source code here.

Java socket client programming techniques

The following Java program demonstrates the following networking programming techniques:

  • How to open a client-side socket.
  • How to set the timeout on a socket.
  • How to write a String to a remote server.
  • How to listen and read the reply from the remote server.

Java socket client: example source code

Given that introduction, and the comments in the code, here is the complete source code for my SimpleSocketClient class:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

/**
 *
 * A complete Java class that demonstrates how to use the Socket
 * class, specifically how to open a socket, write to the socket,
 * and read from the socket.
 *
 * @author alvin alexander, alvinalexander.com.
 *
 */
public class SimpleSocketClient
{

  // call our constructor to start the program
  public static void main(String[] args)
  {
    new SimpleSocketClient();
  }
  
  public SimpleSocketClient()
  {
    String testServerName = "localhost";
    int port = 8080;
    try
    {
      // open a socket
      Socket socket = openSocket(testServerName, port);
      
      // write-to, and read-from the socket.
      // in this case just write a simple command to a web server.
      String result = writeToAndReadFromSocket(socket, "GET /\n\n");
      
      // print out the result we got back from the server
      System.out.println(result);

      // close the socket, and we're done
      socket.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  
  private String writeToAndReadFromSocket(Socket socket, String writeTo) throws Exception
  {
    try 
    {
      // write text to the socket
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
      bufferedWriter.write(writeTo);
      bufferedWriter.flush();
      
      // read text from the socket
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String str;
      while ((str = bufferedReader.readLine()) != null)
      {
        sb.append(str + "\n");
      }
      
      // close the reader, and return the results as a String
      bufferedReader.close();
      return sb.toString();
    } 
    catch (IOException e) 
    {
      e.printStackTrace();
      throw e;
    }
  }
  
  /**
   * Open a socket connection to the given server on the given port.
   * This method currently sets the socket timeout value to 10 seconds.
   * (A second version of this method could allow the user to specify this timeout.)
   */
  private Socket openSocket(String server, int port) throws Exception
  {
    Socket socket;
    
    // create a socket with a timeout
    try
    {
      InetAddress inteAddress = InetAddress.getByName(server);
      SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);
  
      // create a socket
      socket = new Socket();
  
      // this method will block no more than timeout ms.
      int timeoutInMs = 10*1000;   // 10 seconds
      socket.connect(socketAddress, timeoutInMs);
      
      return socket;
    } 
    catch (SocketTimeoutException ste) 
    {
      System.err.println("Timed out waiting for the socket.");
      ste.printStackTrace();
      throw ste;
    }
  }

}

Discussion

As you can see, this sample code is a complete Java socket client class that you can use for your own tests. On my computer this code currently opens a socket to my local computer (“localhost”) on port 8080 (my local Tomcat server), and if that succeeds, it sends to the command GET /\n\n to Tomcat. This is an HTTP command that tells Tomcat to return its root-level document, essentially the same as typing http://localhost:8080/ in your browser.

The program writes that String to Tomcat, gets the results back from Tomcat, and writes the results to standard out (using System.out.println).

As documented in the code, you might want to add a convenience method to this class (or change the current method) so you can set time timeout value dynamically. What I mean by that is that you might want to add a new method with this signature:

Socket openSocket(String server, int port, int timeout) throws Exception

As a final note, here’s a link to more information on setting a Java socket client timeout value, i.e., the number of milliseconds before your socket is considered to be “timed out” in communicating with a server.