[英]Simple 'chat' UDP client and server using Python, can't use `str` as `send()` payload
我正在嘗試在 python 中使用 UDP 進行簡單的“聊天”。 我已經完成了客戶端和服務器代碼,即
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'
如何解決這個問題? 有什么問題嗎?
~
如何解決這個問題? 有什么問題嗎?
嗯:
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 幾乎是將字符串編碼為字節的一種非常好的方法。
給出最少的背景:一個字符串應該真正表現得像一個字符串——即,一段由字母/字形/符號組成的文本,文本的表示,而不是一些二進制內存。 因此,當將一段內存發送給其他人時,您需要確保基於兩端的通用表示(在本例中為 UTF8)理解您的文本。
只需使用fd.sendto(reply.encode(), client_address)
將字符串轉換為字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.