title: How to send serialized data over a TCP connection in java
body: <p>I want to send data which i have serialized over a TCP connection.
  I have created a client/server connection and am sending an Object after serializing it.
  However, I dont know how should i read the data.</p>
  
  <p>here is the code snippet:</p>
  
  <h2>SENDING FUNCTION:</h2>
  
  <pre><code>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();
  }
  </code></pre>
  
  <h2>Function Call:</h2>
  
  <pre><code>String hostname = somevalue;
  int portNo = somevalue;
  Hashtable &lt;Integer, Integer&gt; object = somevalue;
  
  sendTo(hostname,portNo,...,object);
  </code></pre>
  
  <h2>Receiving Function:</h2>
  
  <pre><code>DataInputStream input = new DataInputStream(clientSocket.getInputStream());
  
  int length = input.readInt();
  byte[] bytes = new byte[length];
  input.readFully(bytes);
  
  Hashtable&lt;Integer, Integer&gt; recvObj = (Hashtable&lt;Integer,Integer)programming5.io.Serializer.deserialize(bytes);
  </code></pre>
  
  <p>This is not working. I am getting the following exception:</p>
  
  <p>invalid stream header: 07F8ACED
  java.io.StreamCorruptedException: invalid stream header: 07F8ACED</p>
  
  <p>Please tell me how should i go about this.</p>