TcpClient.java Source code

Java tutorial

Introduction

Here is the source code for TcpClient.java

Source

    //The 3 classes are a a tcp client, tcp server, and a Serializable payload object which is sent from the server to the client.
    //The 3 classes are meant to work together.

    //--George

    //TcpClient.java -------------------------------------------------------------------------------------------------------------------------

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;

/**
 * TcpClient.java
 *
 * This class works in conjunction with TcpServer.java and TcpPayload.java
  *
 * This client test class connects to server class TcpServer, and in response,
* it receives a serialized an instance of TcpPayload.
 */

public class TcpClient
{
    public final static String SERVER_HOSTNAME = "gsoler.arc.nasa.gov";
    public final static int COMM_PORT = 5050;  // socket port for client comms

    private Socket socket;
    private TcpPayload payload;

    /** Default constructor. */
    public TcpClient()
    {
        try
        {
            this.socket = new Socket(SERVER_HOSTNAME, COMM_PORT);
            InputStream iStream = this.socket.getInputStream();
            ObjectInputStream oiStream = new ObjectInputStream(iStream);
            this.payload = (TcpPayload) oiStream.readObject();
        }
        catch (UnknownHostException uhe)
        {
            System.out.println("Don't know about host: " + SERVER_HOSTNAME);
            System.exit(1);
        }
        catch (IOException ioe)
        {
            System.out.println("Couldn't get I/O for the connection to: " +
                SERVER_HOSTNAME + ":" + COMM_PORT);
            System.exit(1);
        }
        catch(ClassNotFoundException cne)
        {
            System.out.println("Wanted class TcpPayload, but got class " + cne);
        }
        System.out.println("Received payload:");
        System.out.println(this.payload.toString());
    }

    /**
     * Run this class as an application.
     */
    public static void main(String[] args)
    {
        TcpClient tcpclient = new TcpClient();
    }
}

    TcpServer.java-------------------------------------------------------------------------------------------------------------------------

    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketException;

/**
 * This class works in conjunction with TcpClient.java and TcpPayload.java
 *
 * This server test class opens a socket on localhost and waits for a client
 * to connect. When a client connects, this server serializes an instance of
 * TcpPayload and sends it to the client.
 */

public class TcpServer
{
    public final static int COMM_PORT = 5050;  // socket port for client comms

    private ServerSocket serverSocket;
    private InetSocketAddress inboundAddr;
    private TcpPayload payload;

    /** Default constructor. */
    public TcpServer()
    {
        this.payload = new TcpPayload();
        initServerSocket();
        try
        {
            while (true)
            {
                // listen for and accept a client connection to serverSocket
                Socket sock = this.serverSocket.accept();
                OutputStream oStream = sock.getOutputStream();
                ObjectOutputStream ooStream = new ObjectOutputStream(oStream);
                ooStream.writeObject(this.payload);  // send serilized payload
                ooStream.close();
                Thread.sleep(1000);
            }
        }
        catch (SecurityException se)
        {
            System.err.println("Unable to get host address due to security.");
            System.err.println(se.toString());
            System.exit(1);
        }
        catch (IOException ioe)
        {
            System.err.println("Unable to read data from an open socket.");
            System.err.println(ioe.toString());
            System.exit(1);
        }
        catch (InterruptedException ie) { }  // Thread sleep interrupted
        finally
        {
            try
            {
                this.serverSocket.close();
            }
            catch (IOException ioe)
            {
                System.err.println("Unable to close an open socket.");
                System.err.println(ioe.toString());
                System.exit(1);
            }
        }
    }

    /** Initialize a server socket for communicating with the client. */
    private void initServerSocket()
    {
        this.inboundAddr = new InetSocketAddress(COMM_PORT);
        try
        {
            this.serverSocket = new java.net.ServerSocket(COMM_PORT);
            assert this.serverSocket.isBound();
            if (this.serverSocket.isBound())
            {
                System.out.println("SERVER inbound data port " +
                    this.serverSocket.getLocalPort() +
                    " is ready and waiting for client to connect...");
            }
        }
        catch (SocketException se)
        {
            System.err.println("Unable to create socket.");
            System.err.println(se.toString());
            System.exit(1);
        }
        catch (IOException ioe)
        {
            System.err.println("Unable to read data from an open socket.");
            System.err.println(ioe.toString());
            System.exit(1);
        }
    }

    /**
     * Run this class as an application.
     */
    public static void main(String[] args)
    {
        TcpServer tcpServer = new TcpServer();
    }
}

    TcpPayload.java-------------------------------------------------------------------------------------------------------------------------

import java.io.Serializable;

/**
 * This class works in conjunction with TcpClient.java and TcpServer.java
 *
 * This class contains test data representing a 'payload' that is sent from
 * TcpServer to TcpClient. An object of this class is meant to be serialized by
 * the server before being sent to the client. An object of this class is meant
 * to be deserialized by the client after being received.
 */

public class TcpPayload implements Serializable
{
    // serial version UID was generated with serialver command
    static final long serialVersionUID = -50077493051991107L;

    private int int1;
    private transient int int2;  // transient members are not serialized
    private float float1;
    private double double1;
    private short short1;
    private String str1;
    private long long1;
    private char char1;

    /** Default constructor. */
    public TcpPayload()
    {
        this.int1 = 123;
        this.int2 = 456;
        this.float1 = -90.05f;
        this.double1 = 55.055;
        this.short1 = 59;
        this.str1 = "I am a String payload.";
        this.long1 = -23895901L;
        this.char1 = 'x';
    }

    /** Get a String representation of this class. */
    public String toString()
    {
        StringBuilder strB = new StringBuilder();
        strB.append("int1=" + this.int1);
        strB.append(" int2=" + this.int2);
        strB.append(" float1=" + this.float1);
        strB.append(" double1=" + this.double1);
        strB.append(" short1=" + this.short1);
        strB.append(" str1=" + this.str1);
        strB.append(" long1=" + this.long1);
        strB.append(" char1=" + this.char1);
        return strB.toString();
    }
}