Click here to Skip to main content
15,886,724 members
Articles / Programming Languages / Java
Tip/Trick

Java - Sockets and Serialization

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
13 May 2015CPOL3 min read 34.7K   485   11  
A guide on sockets, and how to send objects across them

Introduction

Definition: A socket is one end-point of a two-way communication link between two programs running on the network. In other words, a socket is simply an object that allows two (or more) programs to interact on a network.

A socket requires:

  • IP Address: A unique string of numbers that identifies a computer.
  • Port: Every machine has a unique number of ports (65536). Ports are used to identify the data that is sent from a program.

In Java, there are three types of sockets:

  • Stream (TCP) sockets (Socket class)
  • Connectionless (UDP) sockets (Datagramsocket class)
  • Multicastsocket (subclass of Datagramsocket, outside the scope of this article)

Stream socket

Stream socket is a channel between a client and server that uses TCP protocol for data transmission. The Stream socket is reliable since the data is sent and received in similar order.

Datagram socket

Datagram socket is a connectionless socket that uses UDP protocol for data transmission. The Datagram socket is not as reliable as a Stream socket, since data may be lost during transmission.

The Client and Server Architecture

Client/server is a relationship between two programs in which a client (Socket) requests data from a server (ServerSocket).

Client/server architecture is explained in the following steps:

  • A server is running on a specified IP Address and Port.
  • A client attempts to connect to the server using the same IP Address and Port.
  • The server accepts the client and initiates a socket to handle the client.
  • Data transmission begins between the client and server on a network stream.

Serialization

Serialization is the process of translating data (example, employee class) into a format (sequence of bytes) that can later be reconstructed or extracted.


Why use Serialization

Serialization allows us to send a data across a network. For example, if we want to send a student class, we would serialize the class, send it to client, and the client would deserialize it on its side. The advantage of serialization is that it enables us to send multiple data (example: student name, student grade) at once.

Important: Serialization is not secure, meaning that third-party users can still have access to your data. Security is outside the scope of this article.

Using the Code

Create a student class that implements java.io.Serializable and has two properties called studentAvg of type int and studentName of type string. Initiate the getters and setters for the two properties.

Server

Create a new Socket called client that is used to handle connections with a client once a connection is established.

Java
Socket client = null;

The following two objects handle our Serialization operations, ObjectOutputStream writes an object to the stream, ObjectInputStream reads an object from the stream.

Java
ObjectOutputStream out = null;
ObjectInputStream in = null;

Create a new ServerSocket that will listen to a connection on a specified port, the IP Address here is the local machine address 127.0.0.1 since both the client and server will be running on the same machine.

Java
try {
ServerSocket server = new ServerSocket(8888); // start listening on port 8888
Java
client = server.accept(); // this method is a blocking I/O call, it will not be called unless
//a connection is established.
out = new ObjectOutputStream(client.getOutputStream()); // get the output stream of client.
in = new ObjectInputStream(client.getInputStream());    // get the input stream of client.

Student student = (Student) in.readObject(); // cast a Student class from reading the object 
                                             // that was sent to the server by the client. 
System.out.println("Average: " + student.getStudentAvg() + " Name: " + student.getStudentName());
 
// close resources
out.close();
in.close();
client.close();
server.close();


} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}

Client

Create a new Socket called client that is used to handle connections with a server once a connection is established.

Java
Socket client = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;

try {

The following line will try to connect the client to the server on 127.0.0.1 using the specified port 8888.

Java
client = new Socket("127.0.0.1", 8888);
Java
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());

Now, we need to create a Student class and write it into the stream.

Java
Student student = new Student(96, "John");
out.writeObject(student);
out.flush();

//close resources

out.close();
in.close();
client.close();

} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}

Points of Interest

Sockets are widely used, from simple chat applications to large multiplayer games. If you want to get into networking, then sockets are the perfect way to start. More complex projects include multi-threading, handling multiple clients, and security sockets using SSL.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Iraq Iraq
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --