【发布时间】:2016-07-01 14:34:16
【问题描述】:
我将一个对象序列化为字节并发送到服务器端。 在服务器端,我得到了字节流,但我想打印从服务器获取的对象/字符串,以验证我得到了它
服务器端:
CarServerSocket = new ServerSocket(4441);
System.out.println("Server is ready and waiting for connection from client..\n");
try {
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
final DataInputStream bytesIR = new DataInputStream(carSocket.getInputStream());
bytesIRLength = bytesIR.readInt();
while (bytesIRLength > 0) {
byte[] messageIn = new byte[bytesIRLength];
bytesIR.readFully(messageIn,0,messageIn.length);
bytesIR.readUTF();
}
}
}catch(EOFException e ){
System.out.println("\ngot all objects from client.\ndisconnecting server...");
CarServerSocket.close();
carSocket.close();
}
}
客户端-序列化
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes.
我厌倦了使用:toString()、readUTF()...但没有运气。
谁能告诉我如何解决它?
谢谢。
【问题讨论】:
-
您实际上可能想要使用
ObjectInputStream和readObject()方法。当然,那么你会想写信给ObjectOutputStream... -
使用'new String(messageIn)'怎么样?
-
如果您需要有意义的帮助,您需要向我们展示对象被序列化的客户端代码。
-
我不能使用 ObjectOutputStream,因为我必须在服务器端使用 (messageIn,0,messageIn.length)。意味着读取一个字节流并从中提取对象
-
问题的答案仍然取决于数据的发送方式。是 (a)
writeUTF()(b) 一行 (c) 其他吗,如果是,那又是什么?您关于不使用ObjectOutputStream的评论与您序列化对象的声明完全矛盾。是哪个?
标签: java sockets client-server inputstream