A tcp client, a tcp server, and a Serializable payload object which is sent from the server to the client : TCP « Network Protocol « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Network Protocol » TCPScreenshots 
A tcp client, a tcp server, and a Serializable payload object which is sent from the server to the client


//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 = (TcpPayloadoiStream.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();
    }
}


           
       
Related examples in the same category
1. Use the Daytime TCP and Daytime UDP classes
2. Get Socket Infomation
3. Finger Socket
4. Multicast Sniffer
5. Multicast Sender
6. Connects to the default chargen service port
7. Connects to the default echo service port
w___w__w___.j___a___v___a2_s._c___o___m___ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.