Object serialisation via sockets

The ObjectInputStream and ObjectOutputStream wrapper streams are used for serializing and deserializing objects via sockets

constructors

ObjectInputStream ois = new ObjectInputStream (socket.getInputStream());
ObjectOutputStream oos =  new ObjectOutputStream (socket.getOutputStream());

The two main methods are writeObject() and readObject(). An explicit conversion to the object type is necessary during its reconstruction.
An object could be serialized provided its class implements the Serializable interface.
The class definition must be present in both machines!



Example 1

As an example we will use the PersonSr and StudentSr classes defined in 4.


Classes defining transferred objects - must be present in a package visible on the server and on the client:

package student;
import java.io.Serializable;
public class PersonSr implements Serializable{
   
    private static final long serialVersionUID = 1L;
   
    public static int num=0;
    public String name;
    public String id;
    public PersonSr(){
        name = "student "+ ++num;
        id = (int)(Math.random()*3999)+1111+"";
    }
}
-------------------------------------------------------------------------------

package student;
public class StudentSr extends PersonSr{
   
    private static final long serialVersionUID = 1L;
   
    public int notes[];
    public StudentSr(){
        notes = new int [5];
        for(int i =0;i<notes.length;i++){
            notes[i]=(int)(Math.random()*5)+2;
        }
    }
    public String toString(){
       String rez;
            rez = "name:"+name+"\tid:"+id+"\tnotes:";
        for(int i=0;i<notes.length;i++){
            rez += "\t"+notes[i];
        }
        return rez;      
    }
}

 Serialization carried out by the Client class - generation of objects and serialization to the server via socket. The first student with note[0]= 2 completes the application::

package client;
import java.io.*;
import java.net.*;
import student.*;

public class Client {
   
    public static void main(String arg[]) throws IOException{
        ObjectOutputStream oos = null;
        int port = 8089;
        StudentSr s;
        String srv = null;
        InetAddress addr =  InetAddress.getByName(srv);
        System.out.println("addr = " + addr);
        Socket socket = new Socket(addr,port );
        try{
            oos = new ObjectOutputStream (socket.getOutputStream());
            for(;;){
                s =new StudentSr();
                System.out.println(""+s);
                oos.writeObject(s);
                if (s.notes[0]==2)break;
            }
        }
        finally{
            System.out.println ("closing ...");
            socket.close();
        }
    }
}

---------------------------------------------------------------------------------------------------------------------------------

The server classes

The server listens to the network and after the client request - generates an object of class SeveOneClient.
SeveOneClient deserializes the objects, displays them on the server console, ends with the first object received with note[0]= 2 and displays the total number of objects received.

package server;
import java.io.*;
import java.net.*;

public class Srv {
    public static final int PORT = 8089;
    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server Started");
        try {
            while(true) {
                // Blocks until a connection occurs:
                Socket socket = s.accept();              
                    new ServeOneClient(socket);
            }
        } finally {
            s.close();
        }
    }
}

------------------------------------------------------------------------
package server;

import java.io.*;
import java.net.*;
import student.*;

class ServeOneClient extends Thread {
    private Socket socket;
    ObjectInputStream ois = null;
    StudentSr st;
    int cnt_students;

    public ServeOneClient(Socket s)  throws IOException {
        socket = s;
        ois = new ObjectInputStream(socket.getInputStream());
        cnt_students = 0;
        start();    // Calls run()
    }
    public void run()   {
        try {
            while (true) {
                try {
                    st = (StudentSr)ois.readObject();
                    System.out.println(""+st);
                    cnt_students++;
                    if(st.notes[0]==2)break;
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {  }
        finally {
            System.out.println("total "+cnt_students+" students transfered");
            System.out.println("closing...");
            try {
                socket.close();
            } catch(IOException e) {}
        }
    }
}




Modify the example by making all data in the PersonSr and StudentSr classes private