July 28, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Serializing an Object via a Client/Server Connection

  • April 6, 2006
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

This series, The Object-Oriented Thought Process, is intended for someone just learning an object-oriented language and who wants to understand the basic concepts before jumping into the code, or someone who wants to understand the infrastructure behind an object-oriented language he or she is already using. These concepts are part of the foundation that any programmer will need to make the paradigm shift from procedural programming to object-oriented programming.

Click here to start at the beginning of the series.

In keeping with the code examples used in the previous articles, Java will be the language used to implement the concepts in code. One of the reasons that I like to use Java is because you can download the Java compiler for personal use at the Sun Microsystems Web site http://java.sun.com/. You can download the standard edition, J2SE 5.0, at http://java.sun.com/j2se/1.5.0/download.jsp to compile and execute these applications. I often reference the Java J2SE 5.0 API documentation and I recommend that you explore the Java API further. Code listings are provided for all examples in this article as well as figures and output (when appropriate). See the first article in this series for detailed descriptions for compiling and running all the code examples.

In the previous column, you covered several advanced techniques about connecting to a database using Java Database Connectivity (JDBC). Storing data to a database is just one of many ways to save data—a concept called data persistence. In this article, you will explore another aspect of object persistence/serialization, specifically how do you move an object across a client-server connection? You may want to store an object on a machine that is connected to your application via a network connection. You will create a very simple client/server application and transfer an object from the client to the server and back.

Designing the Employee Class

Before you delve into the code to implement the client/server application, you must design a class to be sent across the client/server wire. In short, you will instantiate an object that will be marshaled between the client and the server. Remember that when you say marshaled you mean moving the object between two points. Specifically, the object must be decomposed into a form that can be transported across a wire and then rebuilt on the opposite side of the wire.

In this example, you create a class called Employee. The employee is built from the following specifications:

Two attributes:

  • private int employeeNumber;
  • private String employeeName;

Constructor (set the attributes):

  • Employee(int num, String name)

Methods (getters and setters for the attributes):

  • public int getEmployeeNumber()
  • public void setEmployeeNumber(int num)
  • public String getEmployeeName()
  • public void setEmployeeName(String name)

This class is not going to do a whole lot. It is really only here so you have something to send across the network. What you want to do with your client/server system is this:

  • Instantiate objects of type Employee
  • Set the attributes to some values
  • Send the object from the client to the server
  • Have the server change some of the values
  • Send the object from the server back to the client
  • Verify that the client has the updated information

The complete code for this simple Employee class is shown in Listing 1.

import java.io.*;
import java.util.*;

public class Employee implements Serializable {

   private int employeeNumber;
   private String employeeName;

   Employee(int num, String name) {
      employeeNumber = num;
      employeeName= name;
   }

    public int getEmployeeNumber() {
      return employeeNumber ;
   }

   public void setEmployeeNumber(int num) {
      employeeNumber = num;
   }

   public String getEmployeeName() {
      return employeeName ;
   }

   public void setEmployeeName(String name) {
      employeeName = name;
   }
}

Listing 1: The Employee Object

An important point worthy of interest here is the way the class is defined:

public class Employee implements Serializable

Note the use of the keyword Serializable. This interface identifies that the class can be serialized. The Serializable interface does not actually contain any methods; it is used as a sort of tag that marks the class as Serializable. In the words of the Java 2 API specification: "The serialization interface has no methods or fields and serves only to identify the semantics of being Serializable." At this point, this is all you need to know about serialization; however, you will investigate some interesting issues that pertain to Serializable in a future article.

The sole purpose of the Employee class is to contain the employeeNumber and employeeName. Thus, you can create an instance of this class to demonstrate the specifics of sending it across a client/server network. These attributes, along with their getters/setters, are all you need for this purpose.

The Client

You will first take a look at the Client end of the system. You could just as easily start by developing the Server. In this system, the Client will do the work of creating the Employee object. Thus, it makes sense to start with the Client.

Here are the steps needed to properly demonstrate the features of your client.

  • Create an Employee object
  • Echo the Employee information to confirm the initial values
  • Create a socket
  • Create an ObjectOutputStream
  • Create an InputOutputStream
  • Write the Employee object to the ObjectOutputStream
    • This where the object is sent to the Server
  • Retrieve the updated Employee object from the InputOutputStream
    • After the Server changes it
  • Echo the Employee information to verify the change in values
  • Close the ObjectOutputStream
  • Close the InputOutputStream

Creating the Employee Object

The instantiation of the Employee object is the simplest part of the process. To make things as clean as possible, you create a single object so you don't have to worry about any synchronization. The complete Client.java file can be seen in Listing 2.

For this specific instance, you create an Employee object called joe.

Employee joe = new Employee(150, "Joe");

Make sure that the Client.java file is in the same directory as the Employee.java file. If you decide to use packages, you will have to make sure that your import statements reflect this. You will keep things simple and use the default packaging.

Using the parameters passed to the constructor, the object joe now has an employeeNumber of 150 and an employeeName of "Joe". This is the object that you will send from the Client application to the Server. Note that both the Client and the Server are separate applications and thus they both have a main() method. To get the client/server system up and running, you will have to create a process for both.

Before you start looking at the networking code, the Client first echoes the values of the new joe object, just so you feel confident that the object was created properly.

System.out.println("employeeNumber= " + joe .getEmployeeNumber());
System.out.println("employeeName=   " + joe .getEmployeeName());

Creating the Socket

The first part in connecting to the network is to create a socket using the Socket class. The SDK documentation describes a socket as "an endpoint for communication between two machines".

To use the Socket class, you must import the java.net package.

import java.net.*;

you create an object called socketConnection using the Socket class. The single line of code is as follows.

Socket socketConnection = new Socket ("127.0.0.1", 11111);

This version of the Socket constructor creates a stream socket and connects it to the specified port (11111) number at the specified IP address ("127.0.0.1"). The SDK API states, "you can specify a port number, or 0 to use any free port".

Even though there is not much code needed to create a Socket, two important parameters are passed to the Socket constructor. The first parameter is the URL (actually class InetAddress) of the Server you intend to connect to. This is a String, and the specific URL used here is called a loop-back. The loop-back URL ("127.0.0.1") literally points to the same machine. This is a great technique for testing. With this feature, you can create the Client and the Server on the same machine so that you do not need to have an active network connection to test your applications.

In the next column, I will provide a different URL so that you can test this system over the Internet. In any event, having the option to test the system on a single machine really makes development a lot easier.

The second parameter is an integer and represents a virtual socket that you will associate with this specific client/server application. There is some flexibility with this number; you can vary it. However, the Client and the Server must use the same socket number for this system to work properly.





Page 1 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel