简体   繁体   English

从同一TCP连接发送ByteArray和Bytes

[英]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. 我试图使用单个TCP连接来处理这两种情况,但到目前为止失败了。 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. 请注意,由于外部限制,在我的项目中无法使用socket.io。

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. 您需要设计自己的通信协议,例如http,但是当然要简单得多。 and implement decoder/encoder on both sides 并在两侧实现解码器/编码器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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