Search code examples
javasocketsobjectoutputstream

ObjectOutputStream issue when sending data to a socket


I am listening on a server in my program and when cleint sends a message, I first send a 1-byte ACK back, where 1 byte is msgType that I received.

My program execution flow is something like:

        Socket connection = null;
        connection = serverSocket.accept();
        connection.setKeepAlive(true);
        logger.info("server: connection received from " + connection.getInetAddress().getHostName());
        out = new ObjectOutputStream(connection.getOutputStream());
        
        .
        .

        switch(msgType) {
         case 0:
                // MSG_START
              
                logger.info("Received MSG_START");
                        // send ACK
                sendACK(out, 0);
                logger.info("sent ACK for MSG_START");
                     
                break;
       .

        }

Then I have definition of sendAck function:

private static void sendACK(ObjectOutputStream out, int msgIntType) throws IOException {
    // TODO Auto-generated method stub
    
    byte[] msgType = new byte[1];
    msgType[0] = (byte) (msgIntType & 0xFF);
    logger.debug("Sending message to client: " + msgType.toString());
    out.write(msgType);
    out.flush();
    logger.debug("Sending msg: " + Arrays.toString(msgType));
}

      

Now problem is that at the client end, when client tried in.read(), it gets byteRead as -1 not 1.

What could be the problem here?


Solution

  • ObjectOutputStream is intended for writing Java objects to streams. In this case, i think you should be using a DataOutputStream (and so should the client).

    You would do something like:

    dataOutputStream.writeByte(0);
    

    EDIT: BTW, The client should be using a DataInputStream.