简体   繁体   English

Java TCP。 如何确认收到的数据包是一个完整的数据结构?

[英]Java TCP. How to affirm your received packet is a complete data structure?

I currently have a program that listens and sends on a TCP socket. 我目前有一个侦听和发送TCP套接字的程序。

The problem I'm having is that I send a packet and sometimes it breaks into pieces. 我遇到的问题是我发送了一个数据包,有时会分成几块。 So my listening TCP socket class thinks the first piece that comes in is the entire payload. 所以我的侦听TCP套接字类认为第一个进入的是整个有效负载。

What is the typical approach people take when programming with TCP connections? 人们在使用TCP连接进行编程时采用的典型方法是什么?

You cannot assume that the first piece is the entire payload. 你不能假设第一块是整个有效载荷。 You have to keep reading off the socket until you get all of it. 你必须继续读取插座,直到你得到所有这一切。

There are two options: 有两种选择:

Option 1 选项1
Mark the end of your messages (data structures). 标记消息的结尾(数据结构)。 Your listener then keeps reading until it gets the end-of-message marker. 然后你的听众继续阅读,直到它得到消息结束标记。

Option 2 选项2
Send the length of you message or data structure before you send the actual data. 在发送实际数据之前发送消息或数据结构的长度。 Your listener then keeps reading until its read all the bytes. 然后你的监听器继续读取,直到它读取所有字节。

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

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