1 引子
在Socket通信中,我们要在客户端和服务端中传输数据,传输的数据有各种类型,int,short,long以及String,甚至是自定义的各种Object,我们如何能够保证在服务端和客户端之间的数据能够使得两端都能理解,这就是所谓的“应用协议”;
在通信的“管道”中,流的都是二进制数据,所以,双方如何约定好“解析规则”,则就必须要求通信双方都预先制定好协议;
2 序列化和反序列化
在Java中,有一个借口Serializable接口,这个接口不需要实现实现任何方法,只是一个标识,Java 序列化技术可以使你将一个对象的状态写入一个Byte 流里,并且可以从其它地方把该Byte 流里的数据读出来。重新构造一个相同的对象。这种机制允许你将对象通过网络进行传播,并可以随时把对象持久化到数据库、文件等系统里。
代码如下:
Java代码
Person:
import java.io.Serializable;
import java.util.Date;
public class Person implements Serializable {
private String name;
private int tall;
private transient Date birthday;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTall() {
return tall;
}
public void setTall(int tall) {
this.tall = tall;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address:
package stream.demo;
import java.io.Serializable;
public class Address implements Serializable{
private String city;
private String street;
public Address() {
}
public Address(String city, String street) {
this.city = city;
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
Person:
import java.io.Serializable;
import java.util.Date;
public class Person implements Serializable {
private String name;
private int tall;
private transient Date birthday;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTall() {
return tall;
}
public void setTall(int tall) {
this.tall = tall;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address:
package stream.demo;
import java.io.Serializable;
public class Address implements Serializable{
private String city;
private String street;
public Address() {
}
public Address(String city, String street) {
this.city = city;
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}