Serialisation d'objets via sockets - exemple 2


Classes:: Person  contient deux Strings  - nom et identificateur; constructeur et conversion vers String 
                Student hérite Person et ajout un tableau des notes; constructeur et conversion vers String 
                Les notes terminent avec la première note zero. Les deux classes - dans le package stud

Serveur  - dans son propre package (server). Il soutient  ArrayList des étudiants envoyés par des clients des differents machines virtuelles.
               Affiche des messages de client connecté et déconnecté d'étudiant reçu et sort sur la console la list des étudiants 

Client  -  dans son propre package (client), introduit des étudiants et les envoie vers le serveur. Introduction des notes (entre 0 et 6) continue jusqu'au la première note zero.

Package  stud

package stud;
import java.io.*;
import javax.swing.*;


class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    String name="";
    String id="";
    public Person(){
        do{
            name = JOptionPane.showInputDialog("Please enter person's name");
        } while((name == null)|| (name.length()==0));
       
        do{
            id = JOptionPane.showInputDialog("Please enter person' id");
        } while((id == null)|| (id.length()==0));

    }
    public String toString(){
        return name+" "+id+" ";
    }
}

public class Student extends Person{
    private static final long serialVersionUID = 1L;
    int marks[];
    public Student(){
        marks = new int[5];
        for(int i=0;i<marks.length;i++){
            do{
                String s = JOptionPane.showInputDialog("Please enter marks "+(i+1)+" [0 - 6]");
                if(s==null)s="0";       //to terminate input with cancel
                try{
                    marks[i]= Integer.parseInt(s);
                }
                catch(Exception e){marks[i]=7;}
            } while((marks[i]<0)|| (marks[i]>6));
            if(marks[i]==0)break;           
        }
    }
    public String toString(){
        String s = super.toString()+" marks: ";
        for(int i=0;i<marks.length;i++){
            if(marks[i]==0) break;
            s+=marks[i]+" ";
        }
        return s;
    }
    public String getName(){
        return this.name;
    }
}


Package server

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

class Students{
    private ArrayList<Student>  st;
    public Students(){
        st = new ArrayList<Student>(10);
    }
    public synchronized void addS(Student p){
        st.add(p);
    }
    public synchronized void rmvS(Student p){
        st.remove(p);
    }
    public synchronized int nSt(){
        return st.size();
    }
    public synchronized void printSt(){
        Iterator<Student> itr = st.iterator();
        System.out.println("---------------------------");
        while(itr.hasNext()) {
            Student p=(Student)itr.next();
            System.out.println(""+p);
        }  
        System.out.println(nSt() +" students total\n");  
    }
}
//...............................................................
class ServeOneClient extends Thread {
    private static int number=0;
    private int num;
    private Socket socket;
 
    private ObjectInputStream iStr;
    private Students clt;
    public ServeOneClient(Socket s,Students clt)  throws IOException {
        num= ++number;
        System.out.println("join a new client - with number "+ num);
        socket = s;
        this.clt =clt;
        iStr = new ObjectInputStream(socket.getInputStream());

        // If any of the above calls throw an
        // exception, the caller is responsible for
        // closing the socket. Otherwise the thread
        // will close it.

        start();    // Calls run()
    }
    public void run() {
        try {
            while (true) {
                System.out.println("waiting for new student from client "+num);
                Student s=null;
                try{
                    s = (Student)iStr.readObject();
                }
                catch(ClassNotFoundException exc){}
                if (s == null) break;
                System.out.println("receive student from client "+num+"\t"+s);
                clt.addS(s);
                clt.printSt();
            }

        } catch (IOException e) {  }
        finally {
            try {
                System.out.println("disconecting  client "+num);
                socket.close();
            } catch(IOException e) {}
        }
    }
}

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

                } catch(IOException e) {
                    // If it fails, close the socket,
                    // otherwise the thread will close it:
                    socket.close();
                }
            }
        } finally {
            s.close();
        }
    }
}




Package client

package client;

import java.net.*;
import java.io.*;
import javax.swing.*;
import stud.*;

public class Client {
    BufferedReader in;
    PrintWriter out;
    ObjectOutputStream oStr;
    InetAddress addr;
    Socket socket;
    String name;
    Client(Socket socket){
        this.socket=socket;
        try{

            in =  new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));

            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),true);
            oStr = new ObjectOutputStream(socket.getOutputStream());

        }catch (Exception e){
            System.out.println("exception: "+e);
            System.out.println("closing...");
            try{
                socket.close();
            }catch (java.net.ConnectException e2){
                System.out.println("no server running");
                System.exit(5);
            }catch (IOException e3) {
                System.out.println("no open socket");
                System.exit(6);
            }
        }

    }
    void send(Student s) throws IOException{
        oStr.writeObject(s);
    }
    public static void main(String[] args )throws IOException{       
        Socket socket=null;
        try {
            String server = null;
            InetAddress addr = InetAddress.getByName(server);
            System.out.println("addr = " + addr);
            socket = new Socket(addr, 9595);
            System.out.println("socket = " + socket);
        }
        catch(Exception nos) {
            System.out.println("no server running");
            System.exit(5);
        }
        Client cl= new Client(socket);
        for(;;){
            if(JOptionPane.showConfirmDialog(null, "do you want to introduce a new student?")!=0)break;
            Student st = new Student();          
            cl.send(st);
            JOptionPane.showMessageDialog(null,st+" is send");
        }
        System.out.println("closing...");
        try{
            socket.close();
        }catch (Exception e2){}
    }

}



On peut modifier le serveur pour sauvegarder les étudiants introduits sur  le disque (par exemple dans un fichier "student.ser").
Package server1

package server1;
import java.io.*;
import java.net.*;
import java.util.*;
import stud.*;

class Students{
    private ArrayList<Student>  st;
    @SuppressWarnings("unchecked")
    public Students(){
        ObjectInputStream ois=null;
        st = null;
        try {
            ois = new ObjectInputStream (
                    new FileInputStream ("student.ser"));   
            st= (ArrayList<Student>)ois.readObject();

            ois.close();
        }
        catch(ClassNotFoundException nf) {        }
        catch(IOException iof) {
            System.out.println("there is no student's file sudent.ser");
            st = new ArrayList<Student>(10);
        }
        finally {
            printSt();
        }
    }

    public synchronized void addS(Student p){
        st.add(p);
    }
    public synchronized void rmvS(Student p){
        st.remove(p);
    }
    public synchronized int nSt(){
        return st.size();
    }
    public synchronized void printSt(){
        Iterator<Student> itr = st.iterator();
        System.out.println("---------------------------");
        while(itr.hasNext()) {
            Student p=(Student)itr.next();
            System.out.println(""+p);
        } 
        System.out.println(nSt() +" students total\n"); 
    }
    public synchronized void writeFile() {
        ObjectOutputStream oos=null;
        try {
            oos = new ObjectOutputStream (
                    new FileOutputStream ("student.ser"));   
            oos.writeObject(st);
            oos.close();
        }
        catch(IOException ioe) {}
    }

}
//...............................................................
class ServeOneClient extends Thread {
    private static int number=0;
    private int num;
    private Socket socket;
    private ObjectInputStream iStr;
    private Students clt;
    public ServeOneClient(Socket s,Students clt)  throws IOException {
        num= ++number;
        System.out.println("join a new client - with number "+ num);
        socket = s;
        this.clt =clt;
        iStr = new ObjectInputStream(socket.getInputStream());

        // If any of the above calls throw an
        // exception, the caller is responsible for
        // closing the socket. Otherwise the thread
        // will close it.

        start();    // Calls run()
    }
    public void run()  {
        try {
            while (true) {
                System.out.println("waiting for new student from client "+num);
                Student s=null;
                try{
                    s = (Student)iStr.readObject();
                }
                catch(ClassNotFoundException exc){}
                if (s == null) break;
                System.out.println("receive student from client "+num+"\t"+s);
                clt.addS(s);
                clt.printSt();
            }

        } catch (IOException e) {  }
        finally {
            if(clt.nSt()>0) {
                System.out.println("writing file student.ser");
                clt.writeFile();
            }

            try {
                System.out.println("disconecting  client "+num);
                socket.close();
            } catch(IOException e) {}
        }
    }
}

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

                } catch(IOException e) {
                    // If it fails, close the socket,
                    // otherwise the thread will close it:
                    socket.close();
                }
            }
        } finally {
            s.close();
        }
    }
}