Socket同时使用ObjectInputStream和ObjectOutputStream传输序列化对象时的顺序

在服务器和客户端建立输入输出流:

oos=new ObjectOutputStream(socket.getOutputStream());
ois=new ObjectInputStream(socket.getInputStream());


十分关键的一点是:ObjectInputStream与ObjectOutputStream的顺序问题

在网络通讯中,主机与客户端若使用ObjectInputStream与ObjectOutputStream建立对象通讯,必须注重声明此两个对象的顺序。
如:
主机端先建立ObjectInputStream后建立ObjectOutputStream,则对应地客户端要先建立ObjectOutputStream后建立ObjectInputStream,否则会造成两方互相等待数据而导致死锁。
原因是建立ObjectInputStream对象是需要先接收一定的header数据,接收到这些数据之前会处于阻塞状态


public ObjectInputStream(InputStream in) throws IOException的官方API显示:Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header. 

在创建ObjectInputStream对象时会检查ObjectOutputStream所传过来了头信息,如果没有信息将一直会阻塞


正确的做法:


Server:


socket = ss.accept();
					
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

Client:

Socket socket = new Socket("10.0.2.2", 10000);
socket.setSoTimeout(10000);
				
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

你可能感兴趣的:(Java,android)