java byte连接,使用TCP连接获取字节数组

I was using UDP to send/receive data but I now want to switch to TCP to avoid packet loss.

I've read several tutorials on TCP and noticed that instead of using DatagramPacket like UDP, TCP uses InputStream/OutputStream.

How do we get the byte[] from DataInputStream, something that's similar to this:

byte[] receiveData = new byte[64000];

DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);

receiveData=receivePacket.getData();

解决方案

The answer has 2 parts. Dealing with 2 separate problems your questions is related to.

1. Network facts

TCP is inherently stream based. i.e. Sending byte[1000] first and then byte[1200], is indistinguishable from sending byte[2200] once. What is actually send over the network can very likely be 2 packets, first being a packet with 1400 bytes and the second being 800, or 1401 and 799, and can vary each time. The receiver has no way to know the sender actually sent 1000 bytes first, and then sent 1200 bytes. This is by design in network. Java has nothing to do with this fact. And you can do nothing with it.

2. Java implementation

On the sender side. First, you need OutputStream os = tcpsocket.getOutputStream();. And then, each time, you need os.write(byteArray). On The receiver side, you need InputStream is = tcpsocket.getInputStream();. And then, each time, you need is.read(byteArray). Note that on the receiver side, how much of the byteArray is actually filled will be returned. It may be any number between 1 and the capacity of the byteArray, and is irrelevant to how the sender actually sent it.

To ease the task, you may use DataInputStream is = new DataInputStream(tcpsocket.getInputStream()); at the beginning, and use is.readFully(byteArray) each time you need to read something. This way, it can be guaranteed that byteArray will always be filled.

But you can never know how many bytes you should receive if the actual length is variable unless you add some extra information. For example, send the length first, using 4 bytes. How you will actually do this is usually closely related to your actual use case. And it's up to you

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值