通过缓冲区接收TCP套接字数据
我是否必须从 tcp 套接字获取具有缓冲区大小的数据?我知道数据包是用 \n 划分的,那么有什么方法可以从服务器获取数据,直到我点击 \n 吗? python套接字包有recv()方法,接受缓冲区作为唯一参数。
Do I have to get data from tcp socket with the buffer size? I know the data packages are divided with \n, so is there any way to get data from the server until I hit \n ?
python socket package has recv() method accepting buffer as the only parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不; TCP 不提供任何消息成帧功能。 Recv() 总是会为您提供尽可能多的字节(直到您指定的限制),然后由您的代码来适当地处理这些字节,无论有多少(或多少)由任何传递给您给定的recv()调用。
例如,您可以将接收到的字节添加到缓冲区的末尾,然后在缓冲区中搜索第一个换行符;如果找到,请将其及其前面的内容从缓冲区中删除,并处理删除的文本;重复此操作,直到缓冲区中找不到更多新行。
No; TCP doesn’t provide any message-framing functionality. Recv() will always just give you as many bytes as it can (up to the limit you specified) and then it is up to your code to handle those bytes appropriately regardless of how many (or how few) were passed to you by any given recv() call.
For example you might add the received bytes to the end of a buffer, then search the buffer for the first newline character; if you find one, remove it and whatever precedes it from the buffer and handle the removed text; repeat until no more new lines are found in the buffer.