用于发送和接收用户定义对象的套接字程序不起作用
Posted
技术标签:
【中文标题】用于发送和接收用户定义对象的套接字程序不起作用【英文标题】:Socket program to send and receive user defined objects not working 【发布时间】:2013-12-13 22:10:50 【问题描述】:我有一个用户定义的类 Message,我想在客户端和服务器之间传递它的对象。
Message类如下:
import java.io.Serializable;
public class Message implements Serializable
String CorS;
int data_id;
int status_id;
Integer value;
boolean withdraw;
public Message()
CorS = null;
data_id = 0;
status_id = 0;
value = 0;
withdraw = false;
public Message(String CorS, int data_id, int status_id, Integer value)
this.CorS = CorS;
this.data_id = data_id;
this.status_id = status_id;
this.value = value;
public Message(boolean withdraw)
this.withdraw = withdraw;
客户端向服务器发送对象的代码如下:
Socket s = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
String hostname = null;
int port_no = 0;
HashMap<String, Integer> map = null;
Message m = null;
map = servers.get("Server" + server);
for(String key : map.keySet())
hostname = key;
port_no = map.get(key);
//System.out.println(hostname + " " + port_no);
s = new Socket(hostname, port_no);
in = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
out = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
s_now = s;
m = new Message(client, data, 0, 0);
out.writeObject(m);
out.flush();
System.out.println("Sent obj");
同理,Server端的代码如下:
while (true)
try
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(server.getInputStream()));
//ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());
Message m = (Message) in.readObject();
System.out.println(m.value);
catch (IOException e)
e.printStackTrace();
break;
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
问题是对象没有被打印出来。我得到的输出如下:
Waiting for client on port 1051...
Just connected to /127.0.0.1:59216
在这方面的任何帮助将不胜感激。谢谢:)
【问题讨论】:
【参考方案1】:您需要在两端的ObjectInputStream
之前创建ObjectOutputStream
。
原因是,如 Javadoc 中所述,各个构造函数写入和读取流标头。所以输入流构造函数在对等端的输出流构造函数执行之前不能返回。所以如果你先构造两个输入流,就会出现死锁。
【讨论】:
谢谢。那行得通。但是你能告诉我为什么会这样吗?有什么合理的解释吗?以上是关于用于发送和接收用户定义对象的套接字程序不起作用的主要内容,如果未能解决你的问题,请参考以下文章