简体   繁体   中英

Sending ByteArrays and Bytes from the same TCP connection

In my application I'm create a socket to do communication between a client and a server. There are two types of messages are passing which they differ in-terms of the length of the data. One message type has only one byte, while the other one is of variable length. I was trying to use a single TCP connection to handle both situations, but so far failed. Could someone please tell me what would be the ideal approach for this. Is using two connections with different port numbers would be the best approach? Note that It is impossible to use socket.io in my project due to external constraints.

here's the reading code i'm using:

        Socket socket = new Socket( dstAddress, dstPort );
        InputStream inputStream = socket.getInputStream();
        try( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( 1024 ) )
        {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while( ( bytesRead = inputStream.read( buffer ) ) != -1 )
            {
                byteArrayOutputStream.write( buffer, 0, bytesRead );
            }
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

Thanks

you need to design your own communication protocol, like http for example, but of course much simpler. and implement decoder/encoder on both sides

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM