使用 Python 的简单 'chat' UDP 客户端和服务器,不能使用 `str` 作为 `send()` 负载

Simple 'chat' UDP client and server using Python, can't use `str` as `send()` payload

我正在尝试在 python 中使用 UDP 做一个简单的 'chat'。我已经完成了客​​户端和服务器代码,即

客户

import socket
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM )
udp_ip = '127.0.0.1'
udp_port = 8014
while(True):
    message = input("Client :")
    fd.sendto(message, (udp_ip, udp_port))
    reply = fd.recvfrom(1000)
    print("Server:%s"%(reply))

服务器

import socket
udp_ip = '127.0.0.1'
udp_port = 8014
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fd.bind((udp_ip,udp_port))
while True:
    r = fd.recvfrom(1000)
    print("client : %s"%(r[0]))
    reply = input('server : ')
    client_address = r[1]
    fd.sendto(reply, client_address)  

在客户端,我正在获取

python client.py 
Client :'haii'

在服务器端我得到,

 python server.py 
 client : 'haii'
 server : 'hai there'
 Traceback (most recent call last):
 File "server.py", line 12, in <module>
 fd.sendto(reply, client_address)
 Type Error: a bytes-like object is required, not 'str'  

如何解决这个问题?有什么问题吗?

~

How to solve this problem? Is anything wrong there?

嗯:

fd.sendto(reply, client_address)
Type Error: a bytes-like object is required, not 'str'

如错误所述,您不能直接发送字符串(Python3 字符串不仅仅是一个字节容器);您必须先将其转换为 bytearray

 fd.sendto(bytearray(reply,"utf-8"), client_address)

请注意,您需要指定编码;如果您考虑在字节级别上表示英语中不常见的字符有何不同,那么这很有意义。这种转换的好处是,您可以使用 unicode 发送几乎任何语言的任何文本:

fd.sendto(bytearray("सुंदर भाषा","utf-8"), client_address)

在另一端,你也会收到一个字节的东西,必须先转换成字符串;同样,编码有所不同,您必须使用与发送相同的编码:

r = fd.recvfrom(1000)
received_msg = str(r, "utf-8")

您的 print("%s" % r ) 使用默认编码隐式调用 str,但这在网络中很可能不是一个好主意。使用 utf-8 是将字符串编码为字节的非常好的方法。

给出最少量的背景:一个字符串应该真正表现得像一个字符串——即,一段由 letters/glyphs/symbols 组成的文本,text 的表示,而不是一些二进制内存。因此,当将一段记忆发送给其他人时,您需要确保您的文本基于通用表示形式被理解,在本例中为两端的 UTF8。

只需使用 fd.sendto(reply.encode(), client_address) 将字符串转换为字节。