Srikanth Technologies

Sockets and Serialization in Java

In this blog I will show how to serialize a Java object from Server Socket to Client Socket.

The following are different components used in this blog :

Here is screenshot of NetBeans Projects window with all projects.

Creating Library

We want to use Contact class in both Client and Server applications. So we want to provide it in a separate .jar file so that it can be used in multiple applications.

Here are the steps to create Contacts library.

  1. Start NetBeans
  2. Select File -> New Project. Select Java in Categories and Java Application in Projects. Click Next
  3. Enter project name as Contacts
  4. Once project is created, select Source Packages. Invoke popup menu and select New -> Java Class
  5. Enter Contact as classname and contacts in package name
  6. Type the following code for Contact class

    package contacts;
    import java.io.Serializable;
    public class Contact implements Serializable {
        private String name, mobile, email;
        public Contact(String name, String mobile, String email) {
            this.name = name;
            this.mobile = mobile;
            this.email = email;
        }
        public Contact() {
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getMobile() {
            return mobile;
        }
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }     
  7. Select Run -> Build Project(contacts). It creates contacts.jar in dist folder under project folder

Server Application

All that we have in server application is a single class with main() method. It creates a server socket to receive name from client and send contact object.

In order to use Contact class in contacts.jar, we need to add contacts.jar to libraries node in ContactsServer application.

Here are the steps to create server:

  1. In NetBeans, select File -> New Project. Select Java in Categories and Java Application in Projects
  2. Enter ContactsServer as project name
  3. Once project is created, select Libraries node and select Add Jar/Folder option from Popup menu and select contacts.jar from dist folder of Contacts application
  4. Select Source Packages. Invoke popup menu and select New -> Java Class
  5. Enter Server as classname and enter the following code :

    import contacts.Contact;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class Server {
        public static void main(String[] args) throws Exception {
            ArrayList<Contact>  contacts = new ArrayList<>();
            contacts.add(new Contact("Steve","9090909090","steve@gmail.com"));
            contacts.add(new Contact("Bill","9988776655","bill@hotmail.com"));
            contacts.add(new Contact("Jack","9876543210","jack@yaho.com"));
            contacts.add(new Contact("Larry","8877996655","larry@gmail.com"));
    
            ServerSocket serversocket  = new ServerSocket(1133,10);
            System.out.println("Contacts server is ready ....");
    
            while(true) {
                Socket client = serversocket.accept();
                // take input and output streams
                Scanner scanner  = new Scanner(client.getInputStream());
                ObjectOutputStream oos  = new ObjectOutputStream( client.getOutputStream());
                // find contact with the given name
                String name = scanner.nextLine();
                boolean found = false;
                for(Contact c : contacts) {
                    if ( c.getName().equals(name))
                    {
                        found = true;
                        oos.writeObject(c);  // serialize object and send to client 
                    }
                }
                if (!found) {
                    // write Contact object only with name when name is not found
                    oos.writeObject(new Contact(name,null,null)); 
                }
                client.close();
            } // while 
        } // main()
    } // class
    
  6. Run Server (Server.java) to create a server socket that listens on port number 1133

Client Application

Client application takes name from user, sends it to server and reads Contact object from server. If name is found on server, it gets a Contact object with all details otherwise it gets Contact object with mobile and email set to null.

Here are steps to create client application:

  1. In NetBeans, select File -> New Project. Select Java in Categories and Java Application in Projects
  2. Enter ContactsClient as project name
  3. Once project is created, select Libraries node and select Add Jar/Folder option from Popup menu and select contacts.jar from dist folder of Contacts application
  4. Select Source Packages. Invoke popup menu and select New -> Java Class
  5. Enter Client as classname and enter the following code :

    import contacts.Contact;
    import java.io.ObjectInputStream;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.util.Scanner;
    
    public class Client {
        public static void main(String[] args) throws Exception  {
                Socket socket  = new Socket("localhost",1133);
                Scanner scanner  = new Scanner(System.in);
                ObjectInputStream ois  = new ObjectInputStream( socket.getInputStream());
                // take name from keyboard
                System.out.print("Enter person name : ");
                String name = scanner.nextLine();
                
                PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
                pw.println(name);
                
                // read Contact object from server and deserialize it
                Contact contact = (Contact) ois.readObject();
    
                if ( contact.getMobile() == null) // contact not found
                     System.out.printf("Sorry! %s not found\n", name);
                else
                {
                     System.out.println("Mobile   : " + contact.getMobile());
                     System.out.println("Email    : " + contact.getEmail());
                }
        }
    }
    
  6. While server is running, run client and enter Bill as name. It should display mobile and email of Bill as follows :

    Enter person name : Bill 9988776655
    Email    : bill@hotmail.com