程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 通過socket傳遞java對象(對象序列化)

通過socket傳遞java對象(對象序列化)

編輯:關於JAVA

這篇文章主要實現的是j:通過socket傳遞Java對象。采用的方法就是對象序列化。方法是:通過socket建立c/s連接;通過ObjectOutputStream,ObjectOutputStream 讀寫對象。唯一需要留意的是傳遞的java 對象需要實現Serializable標記接口。代碼包括:Java對象類,Employee; socket clIEnt類;server類。主要代碼如下:

Java對象類:

import Java.io.*;

import Java.util.*;

public class Employee implements Serializable {

private int employeeNumber;

private String employeeName;

Employee(int num, String name) {

employeeNumber = num;

employeeName= name;

}

public int getEmployeeNumber() {

return employeeNumber ;

}

public void setEmployeeNumber(int num) {

employeeNumber = num;

}

public String getEmployeeName() {

return employeeName ;

}

public void setEmployeeName(String name) {

employeeName = name;

}

}

clIEnt類:

import java.io.*;import Java.Net.*;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); } }}

Server類:

import Java.io.*;

import Java.Net.*;

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

}

}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved