关于Java Socket网络传输的序列化机制

发布时间:2016-10-31 00:00:00 编辑:嘉辉 手机版

  采用Java Socket网络传输的序列化机制,将对象“压扁”成二进制字节,将二进制字节在网络中传输;

  自定义协议,将对象用字符串描述出来,将字符串用二进制表示,在网络中传输,在另外一边用相反的策略解析这个字符串,重新构造业务对象,这个方法能够在异构平台中进行传输而不变形,但是需要额外的编写“压扁”和“充气”的代码;

  我们这里用第一种方法:

  1.package stream.demo;

  2.import java.io.ByteArrayInputStream;

  3.import java.io.ByteArrayOutputStream;

  4.import java.io.File;

  5.import java.io.FileInputStream;

  6.import java.io.FileOutputStream;

  7.import java.io.IOException;

  8.import java.io.InputStream;

  9.import java.io.ObjectInputStream;

  10.import java.io.ObjectOutputStream;

  11.import java.io.OutputStream;

  12.import java.util.Date;

  13.public class Persistence {

  14.public static void main(String[] args) {

  15.byte[] bs = Persistence.toBytes();

  16.//在网络中进行传输

  17.Persistence.getBytes(bs);

  18.}

  19.public static byte[] toBytes() {

  20.Person p = new Person();

  21.p.setName("corey");

  22.p.setTall(171);

  23.p.setBirthday(new Date());

  24.p.setAddress(new Address("yiyang", "ziyang"));

  25.ByteArrayOutputStream out = new

  ByteArrayOutputStream();

  26.try {

  27.ObjectOutputStream oout = new ObjectOutputStream(out);

  28.oout.writeObject(p);

  29.} catch (IOException e) {

  30.// TODO Auto-generated catch block

  31.e.printStackTrace();

  32.}

  33.return out.toByteArray();

  34.}

  35.public static void getBytes(byte[] bs) {

  36.try {

  37.ByteArrayInputStream byteIn = new

  ByteArrayInputStream(bs);

  38.ObjectInputStream in = new ObjectInputStream(byteIn);

  39.Person p = (Person) in.readObject();

  40.System.out.println(p.getName());

  41.System.out.println(p.getTall());

  42.System.out.println(p.getBirthday());

  43.System.out.println(p.getAddress().getCity());

  44.System.out.print(p.getAddress().getStreet());

  45.} catch (Exception e) {

  46.// TODO Auto-generated catch block

  47.e.printStackTrace();

  48.}

  49.}

  50.}

  其中服务端代码片段为:

  51.in = this.getRequestSocket().getInputStream();

  52.out = this.getRequestSocket().getOutputStream();

  53.byte[] bs = Persistence.toBytes();

  54.System.out.println("发送数字长度:"+bs.length);

  55.out.write(bs);

  56.this.getRequestSocket().close();

  57.客户端代码片段为:

  58.InputStream in = request.getInputStream();

  59.byte[] bin = new byte[200];

  60.int length = 0;

  61.while ((length = in.read(bin)) != -1) {

  62.System.out.println("length:" + length);

  63.Persistence.getBytes(bin);

  64.}

本文已影响861
+1
0