Serialisation d'objets via sockets

Les flux enveloppes ObjectInputStream et ObjectOutputStream sont utilisés pour la sérialisation et la désérialisation des objets via sockets

constructeurs

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

Les deux méthodes principales sont writeObject() et readObject(). Une conversion explicite vers le type d'objet est nécessaire pendant son reconstruction.
Un objet pourrait être sérialisé à condition que sa classe implémente l'interface Serializable.


Exemple 1

Comme exemple on va utiliser les classes PersonSr et StudentSr de 2.4


Les classes client:

import java.io.Serializable;
public class PersonSr implements Serializable{
    static int num=0;
    String name;
    String id;
    PersonSr(){
        name = "student "+ ++num;
        id = (int)(Math.random()*3999)+1111+"";
    }
}   
public class StudentSr extends PersonSr{
    int notes[];
    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;       
    }
}

Serialisation réalisé par la classe Client - générations des objets et serialisation vers le serveur via socket. Le premier student avec note[0]= 2   termine l'application:

import java.io.*;
import java.net.*;
public class Client {
   
    public static void main(String arg[]) throws IOException{
        ObjectOutputStream oos = null;
        int port = 8080;
        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();
        }
    }
}

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

Les classes serveur:

Il faut declarer les classes PersonSr et StudentSr :


import java.io.Serializable;
public class PersonSr implements Serializable{
    static int num=0;
    String name;
    String id;
    PersonSr(){
        name = "student "+ ++num;
        id = (int)(Math.random()*3999)+1111+"";
    }
}   
public class StudentSr extends PersonSr{
    int notes[];
    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;       
    }
}

Le serveur écoute le réseau et après la demande de client - génère un objet de classe SeveOneClient.
SeveOneClient déserialise les objets, les affiche sur la console de serveur, finit avec le premier objet reçu avec note[0]= 2 et affiche le nombre total des objets reçus.

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

public class Srv {
    public static final int PORT = 8080;
    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();
        }
    }
}

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

import java.io.*;
import java.net.*;
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) {}
        }
    }
}