我正在尝试使用套接字从服务器向客户端发送自定义对象(Info
)。信息类代码为:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Info implements Serializable {
private static final long serialVersionUID = -8967456786256719218L;
private String ip;
private int port;
private List<String> responsibilityLines;
public Info(String ip, int port, List<String> responsibilityLines) {
this.ip = ip;
this.port = port;
this.responsibilityLines = responsibilityLines;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getSubscriberPort() {
return port;
}
public void setSubscriberPort(int port) {
this.port = port;
}
public List<String> getResponsibilityLines() {
return responsibilityLines;
}
public void setResponsibilityLines(ArrayList<String> responsibilityLines) {
this.responsibilityLines = responsibilityLines;
}
@Override
public String toString() {
return "Info{" +
"ip='" + ip + '\'' +
", port=" + port +
", responsibilityLines=" + responsibilityLines +
'}';
}
}
套接字连接已建立,并且其他任何Java对象或原始类型也已成功发送。但是,当我尝试发送Info
对象的列表时,客户端将阻塞并等待接收(这永远不会发生)。要从服务器发送对象,请使用:
List<Info> infoList = new ArrayList<>();
Info inf = new Info("192.168.78.45", 3456, null);
infoList.add(inf);
dos.writeObject(infoList);
dos.flush();
并接收我使用的对象:
List<Info> infoList;
infoList = (List<Info>) dis.readObject();
dos是ObjectOutputStream
,dis是ObjectInputStream
。
答案 0 :(得分:0)
使用ByteArrayOutputStream
作为ObjectOutputStream()
的输入
ByteArrayOutputStream bos = new ByteArrayOutputStream()
ObjectOutputStream oos = new ObjectOutputStream(bos)
oos.writeObject(infoList)
oos.close
假设您的服务器知道谁可以解析信息类。