开发者

ObjectOutputStream issue when sending data to a socket

开发者 https://www.devze.com 2023-02-28 08:50 出处:网络
I am lsitening 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.

I am lsitening 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 -开发者_JS百科1 not 1.

What could be the problem here ?

Thanks in advance, -JJ


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.


Despite your acceptance rate...

You are using a ObjectOutputStream to send acknowledgement, but this type of stream uses a special protocol as described in the Java Serialization specification. Such protocol is subject to certain headers sent prior to the actual payload.

Therefore, it is best is you use other kind of stream that is not subject to these decorations.

0

精彩评论

暂无评论...
验证码 换一张
取 消