Objects serialisation via sockets - example 2


Classes:    Person contains two Strings - name and identifier; constructor and conversion to String
                 Student inherits Person and adds a grade table; constructor and conversion to String
                 The notes end with the first zero note. Both classes - in the stud package


Server - in its own package (server). It supports ArrayList of students sent by clients of different virtual machines.
                Displays connected and disconnected student client messages received and outputs the list of students to the console


Client - in its own package (client), introduces students and sends them to the server. Introduction of notes (between 0 and 6) continues until the first 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){}
    }

}



The server can be modified the to save the students entered on disk (for example in a "student.ser" file).

     *
In the constructor of the shared object, instead of creating an empty list, it will be loaded from a file. If the file does not exist, an empty list will be created.
     * The list must be saved again in the file when a thread disconnects from the client.
     * The serialization is done by a synchronized method - open the file, write entire list, close the file.


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();
        }
    }
}