我正在尝试实现对象序列化,但仍然遇到了StreamCorruptedException。
在服务器端:
public class MulticastServer {
public static void main(String[] args) throws java.io.IOException {
new MulticastServerThread().start();
}
}
哪个电话:
public class MulticastServerThread extends QuoteServerThread {
boolean moreQuotes=true;
public void run() {
while (moreQuotes) {
try {
byte[] buf = new byte[256];
String dString="Server";
System.out.println(dString);
buf = dString.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buf, buf.length,
group, 4446);
socket.send(packet);
ObjectInputStream is=null;
ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
is = new ObjectInputStream(new BufferedInputStream(byteStream));
Object o1=(Object)is.readObject();
System.out.println(o1.a);
is.close();
socket.close();
}}}}
服务器和客户端上的Object类:
public class Object implements Serializable{
private static final long serialVersionUID=1L;
int a=10;
}
和客户端代码:
public class MulticastClient {
public static void main(String[] args) throws IOException {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
Object o1=new Object();
DatagramPacket packet;
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("received data" +received);
ObjectOutputStream os = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(15000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.writeObject((Object)o1);
System.out.println(o1.a);
os.flush();
}
socket.leaveGroup(address);
socket.close();
}
}
我已经完成了所有这些:
有人可以帮帮我吗?谢谢!
答案 0 :(得分:1)
如果您尝试通过UDP进行对象序列化,则需要将对象序列化为数据包的字节数组,并从接收端读取该对象。有一篇旧的Java World文章:Object transport via datagram packets,你可能觉得它很有用。
看起来您想要实现双向通信:
server -> send packet
client -> receive packet
client -> send object
server -> receive object
我不确定这对你有多大帮助(特别是如果你有多个客户)。
但至少需要进行以下更改才能使任何工作正常运行:
receive
调用。send
数据包中的对象。