關於Java Socket網絡傳輸的序列化機制

採用Java Socket網絡傳輸的`序列化機制,將對象“壓扁”成二進制字節,將二進制字節在網絡中傳輸;

關於Java Socket網絡傳輸的序列化機制

自定義協議,將對象用字符串描述出來,將字符串用二進制表示,在網絡中傳輸,在另外一邊用相反的策略解析這個字符串,重新構造業務對象,這個方法能夠在異構平臺中進行傳輸而不變形,但是需要額外的編寫“壓扁”和“充氣”的代碼;

我們這裏用第一種方法:

age ;

rt ArrayInputStream;

rt ArrayOutputStream;

rt ;

rt InputStream;

rt OutputStream;

rt ception;

rt tStream;

rt ctInputStream;

rt ctOutputStream;

rt utStream;

rt ;

ic class Persistence {

ic static void main(String[] args) {

[] bs = tes();

16.//在網絡中進行傳輸

ytes(bs);

18.}

ic static byte[] toBytes() {

on p = new Person();

ame("corey");

all(171);

irthday(new Date());

ddress(new Address("yiyang", "ziyang"));

ArrayOutputStream out = new

ByteArrayOutputStream();

{

ctOutputStream oout = new ObjectOutputStream(out);

eObject(p);

29.} catch (IOException e) {

30.// TODO Auto-generated catch block

tStackTrace();

32.}

rn teArray();

34.}

ic static void getBytes(byte[] bs) {

{

ArrayInputStream byteIn = new

ByteArrayInputStream(bs);

ctInputStream in = new ObjectInputStream(byteIn);

on p = (Person) Object();

tln(ame());

tln(all());

tln(irthday());

tln(ddress()ity());

t(ddress()treet());

45.} catch (Exception e) {

46.// TODO Auto-generated catch block

tStackTrace();

48.}

49.}

50.}

其中服務端代碼片段爲:

= equestSocket()nputStream();

= equestSocket()utputStream();

[] bs = tes();

tln("發送數字長度:"+th);

e(bs);

equestSocket()e();

57.客戶端代碼片段爲:

tStream in = nputStream();

[] bin = new byte[200];

length = 0;

e ((length = (bin)) != -1) {

tln("length:" + length);

ytes(bin);

64.}