package com.gas.test.socketObjTransfer;
import java.io.Serializable;
public class Employee implements Serializable{
private int employeeNumber;
private String employeeName;
public Employee(int employeeNumber,String employeeName) {
this.employeeName = employeeName;
this.employeeNumber = employeeNumber;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
///
package com.gas.test.socketObjTransfer;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] arg) {
Employee employee = null;
try {
ServerSocket socketConnection = new ServerSocket(11111);
System.out.println("Server Waiting");
Socket pipe = socketConnection.accept();
ObjectInputStream serverInputStream = new
ObjectInputStream(pipe.getInputStream());
ObjectOutputStream serverOutputStream = new
ObjectOutputStream(pipe.getOutputStream());
employee = (Employee )serverInputStream.readObject();
employee .setEmployeeNumber(256);
employee .setEmployeeName("John");
serverOutputStream.writeObject(employee);
serverInputStream.close();
serverOutputStream.close();
} catch(Exception e) {System.out.println(e);
}
}
}
package com.gas.test.socketObjTransfer;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] arg) {
try {
Employee joe = new Employee(150, "Joe");
System.out.println("employeeNumber= " + joe.getEmployeeNumber());
System.out.println("employeeName= " + joe.getEmployeeName());
Socket socketConnection = new Socket("127.0.0.1", 11111);
ObjectOutputStream clientOutputStream = new ObjectOutputStream(
socketConnection.getOutputStream());
ObjectInputStream clientInputStream = new ObjectInputStream(
socketConnection.getInputStream());
clientOutputStream.writeObject(joe);
joe = (Employee) clientInputStream.readObject();
System.out.println("employeeNumber= " + joe.getEmployeeNumber());
System.out.println("employeeName= " + joe.getEmployeeName());
clientOutputStream.close();
clientInputStream.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
java socket传递数据对象
最新推荐文章于 2022-12-02 08:57:47 发布