python - 类型错误 : a bytes-like object is required, 不是 'str'

标签 python python-3.x sockets

以下是尝试使用套接字修改用户提供的输入的代码:

from socket import *

serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print (modifiedMessage)
clientSocket.close()

当我执行它并提供输入时,会发生以下错误:

Input lowercase sentence:fdsgfdf
Traceback (most recent call last):
  File "C:\srinath files\NETWORKS\UDPclient.py", line 6, in <module>
    clientSocket.sendto(message,(serverName, serverPort))
TypeError: a bytes-like object is required, not 'str'

我能做些什么来解决这个问题?

最佳答案

此代码适用于 Python 2。但在 Python 3 中,会导致位编码错误。我试图制作一个简单的 TCP 服务器并遇到了同样的问题。编码解决了这个问题。用 sendto 命令试试这个。

clientSocket.sendto(message.encode(),(serverName, serverPort))

同样,如果您想完全按照发送的方式打印数据,您应该使用 .decode() 在 UDP 服务器端接收数据。

关于python - 类型错误 : a bytes-like object is required, 不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003498/

相关文章:

python - Inno Setup runhidden 标志不适用于从批处理文件执行的控制台应用程序

python - 将字符串列表的列表转换为 float 的 ndarray

python - 是否可以通过Python3中的属性来确定方法是否被调用?

python - Request.Response 对象不会重定向到正确的 URL

python - 使用python在Land中查找最近的位置坐标

Python:如何创建一个循环来更改经度数据

python - 如何更优雅地将一对键值对的字典解包为两个变量?

C - 来自文件描述符的公共(public) IP

WCF 双工、套接字编程、RabbitMQ

c - recvfrom 调用时出现段错误