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