![](/img/trans.png)
[英]How to send a serialized class over sockets using TCP protocal in Java?
[英]How to send serialized data over a TCP connection in java
我想發送已通過TCP連接序列化的數據。 我創建了一個客戶端/服務器連接,並在序列化之后發送一個對象。 但是,我不知道該如何讀取數據。
這是代碼片段:
sendTo(String receiverAddr, int receiverPort,....., Object data) {
.
.
.
if (data != null) {
byte[] byteObj = programming5.io.Serializer.serializeBytes(data);
output.writeInt(byteObj.length);
output.write(byteObj, 0, byteObj.length);
output.flush();
}
output.close();
sock.close();
}
String hostname = somevalue;
int portNo = somevalue;
Hashtable <Integer, Integer> object = somevalue;
sendTo(hostname,portNo,...,object);
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
int length = input.readInt();
byte[] bytes = new byte[length];
input.readFully(bytes);
Hashtable<Integer, Integer> recvObj = (Hashtable<Integer,Integer)programming5.io.Serializer.deserialize(bytes);
這是行不通的。 我收到以下異常:
無效的流頭:07F8ACED java.io.StreamCorruptedException:無效的流頭:07F8ACED
請告訴我我應該怎么做。
使用ObjectOutputStream
寫入對象,並使用ObjectInputStream
讀取對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.