爪哇 TCP.如何确认你收到的数据包是完整的数据结构? [英] Java TCP. How to affirm your received packet is a complete data structure?

查看:35
本文介绍了爪哇 TCP.如何确认你收到的数据包是完整的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个程序可以在 TCP 套接字上侦听和发送.

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?

推荐答案

您不能假设第一部分是整个有效负载.您必须不断读取套接字,直到读完为止.

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.

有两种选择:

选项 1
标记消息(数据结构)的结尾.然后,您的听众会继续阅读,直到获得消息结束标记.

Option 1
Mark the end of your messages (data structures). Your listener then keeps reading until it gets the end-of-message marker.

选项 2
在发送实际数据之前发送消息或数据结构的长度.然后您的侦听器继续读取,直到读取所有字节.

Option 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.

这篇关于爪哇 TCP.如何确认你收到的数据包是完整的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆