自定义通讯协议时,bean序列化

1,bean实体类,协议类。

package com.wizarpos.protocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

/**
 * @author harlen
 * @time 2018年1月15日 上午10:56:22
 * @email [email protected]
 * @description 自定义通讯协议时,bean序列化。
 */
public class MyTCP implements Serializable {
	private static final long serialVersionUID = 1L;
	private int type;
	private int length;
	private String data;

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
}
2,测试类

package com.wizarpos.protocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author harlen
 * @time 2018年1月15日 下午1:58:50
 * @email [email protected]
 * @description 测试类
 */
public class App {
	public static void writeMyTCP(MyTCP myTCP, OutputStream os) throws IOException {
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeInt(myTCP.getType());
		dos.writeInt(myTCP.getLength());
		dos.write(myTCP.getData().getBytes());
		dos.close();
	}

	public static MyTCP readMyTCP(InputStream is) throws IOException {
		MyTCP myTCP = new MyTCP();
		DataInputStream dis = new DataInputStream(is);
		int type = dis.readInt();
		int length = dis.readInt();
		byte[] data = new byte[length];
		dis.read(data, 0, length);
		myTCP.setType(type);
		myTCP.setLength(length);
		myTCP.setData(new String(data));
		dis.close();
		return myTCP;

	}

	public static void main(String[] args) throws Exception {
		MyTCP myTCP = new MyTCP();
		myTCP.setType(10);
		String data = "自定义通讯协议时,bean序列化。";
		myTCP.setData(data);
		myTCP.setLength(data.getBytes().length);
		FileOutputStream os = new FileOutputStream(new File("tcp.dat"));
		writeMyTCP(myTCP, os);
		os.close();
		FileInputStream is = new FileInputStream(new File("tcp.dat"));
		MyTCP readMyTCP = readMyTCP(is);
		is.close();
		System.out.println(readMyTCP.getType());
		System.out.println(readMyTCP.getLength());
		System.out.println(new String(readMyTCP.getData()));

	}
}



猜你喜欢

转载自blog.csdn.net/fhl13017599952/article/details/79062722