Сериализация на обекти през сокети
Пример
Класове: Person с два
стринга - име и идентификатор, конструктор и преобразуване до стринг
Student наследява Person и добавя масив от оценки,
конструктор, преобразуване до стринг
Оценките
се извеждат до първа нулева оценка. Двата класа - в отделен пакет - stud
Сървър - в отделен пакет (server)поддържа
ArrayList от студенти, които
му се изпращат от клиенти от други машини
извежда
съобщение за свързан и прекъснал връзката клиент, за получен студент и
извежда на
конзола
получените до момента студенти.
Клиент - в отделен пакет (client),
въвежда студенти и ги изпраща на сървъра. Въвеждането на оценки (между
0 и 6) продължава до
отказ или
до въвеждане на оценка 0
Пакет 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;
}
}
пакет 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 BufferedReader in;
private PrintWriter out;
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;
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
out = new PrintWriter( new
BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
),
true);
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();
}
}
}
пакет
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(){
try{
String server
= null;
InetAddress
addr = InetAddress.getByName(server);
System.out.println("addr = " + addr);
socket = new
Socket(addr, 9595);
System.out.println("socket = " + socket);
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
(Exception e2){
System.out.println("no server running");
System.exit(5);
}
}
}
void send(Student s) throws IOException{
oStr.writeObject(s);
}
public static void main(String[] args )throws
IOException{
Client cl= new Client();
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");
}
}
}