如何正确使用recv函数进行TCP聊天,python3? [英] How to properly use recv function for TCP chat, python3?

查看:24
本文介绍了如何正确使用recv函数进行TCP聊天,python3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些消息来源说 recv 应该具有消息的最大长度,例如 recv(1024):

Some sources say that recv should have the max length possible of a message, like recv(1024):

message0 = str(client.recv(1024).decode('utf-8'))

但其他消息来源说它应该包含接收消息的总字节数.如果消息是你好":

But other sources say that it should have the total bytes of the receiving message. If the message is "hello":

message0 = str(client.recv(5).decode('utf-8'))

recv() 的正确使用方法是什么?

推荐答案

一些消息来源说......但其他消息来源说......消息......

Some sources say ... But other sources say ... message ...

两个来源都是错误的.

recv 的参数是想要一次读取的最大字节数.

使用 UDP 套接字,这是消息大小想要读取的或更大,但只有一个 recv 无论如何只会返回一条消息.如果给定的大小小于消息,它将被修剪,其余的将被丢弃.

With an UDP socket this is the message size one want to read or larger, but a single recv will only return a single message anyway. If the given size is smaller than the message it will be pruned and the rest will be discarded.

使用 TCP 套接字(您询问的情况)首先没有消息的概念,因为 TCP 只是一个字节流.recv 将简单地返回可用字节数以供读取,直到给定的大小.具体而言,TCP 接收方中的单个 recv 不需要匹配发送方中的单个 send.可能会匹配,数据量少的时候经常会匹配,但不能保证,绝对不能依赖.

With a TCP socket (the case you ask about) there is no concept of a message in the first place since TCP is a byte stream only. recv will simply return the number of bytes available for read, up to the given size. Specifically a single recv in a TCP receiver does not not need to match a single send in the sender. It might match and it often will match if the amount of data is small, but there is no guarantee and one should never rely on it.

... message0 = str(client.recv(5).decode('utf-8'))

... message0 = str(client.recv(5).decode('utf-8'))

请注意,直接对 recv 返回的数据调用 decode('utf-8') 是一个坏主意.首先需要确保读取了所有预期数据,然后才调用 decode('utf-8').如果仅读取部分数据,则读取数据的结尾可能位于字符的中间,因为 UTF-8 中的单个字符可能被编码为多个字节(除 ASCII 字符外的所有字符).如果 decode('utf-8') 使用不完整的编码字符调用,它将抛出异常并且您的代码将中断.

Note that calling decode('utf-8') directly on the data returned by recv is a bad idea. One first need to be sure that all the expected data are read and only then call decode('utf-8'). If only part of the data are read the end of the read data could be in the middle of a character, since a single character in UTF-8 might be encoded in multiple bytes (everything except ASCII characters). If decode('utf-8') is called with an incomplete encoded character it will throw an exception and your code will break.

这篇关于如何正确使用recv函数进行TCP聊天,python3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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