簡體   English   中英

如何在Java中通過TCP連接發送序列化數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM