hhhljy 发表于 2021-11-10 13:45:20

python 使用socket .sendto的问题

代码如下:
from socket import *
serverName = b'host'
serverPort = b'12000'
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = input('input lowercase sentence:')
message = message.encode()
clientSocket.sendto(message,(serverName,serverPort))
modifiedMessage,serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage)
clientSocket.close()

提示错误如下:
Traceback (most recent call last):
File "C:/Users/lin/Desktop/UDPclient.py", line 7, in <module>
    clientSocket.sendto(message,(serverName,serverPort))
TypeError: 'bytes' object cannot be interpreted as an integer

求教,谢谢

suchocolate 发表于 2021-11-10 14:34:13

serverName = 'host'
serverPort = 12000

hhhljy 发表于 2021-11-10 14:44:48

suchocolate 发表于 2021-11-10 14:34


我第一次也是这样写的,会提示要使用bytes的格式
我查了,在python2里面是不分bytes和str的,在python3里面就要分了,所以我对格式进行了转换
使用你改的这个会报下面这个错误
Traceback (most recent call last):
File "C:\Users\lin\Desktop\UDPclient.py", line 6, in <module>
    clientSocket.sendto(message,(serverName,serverPort))
TypeError: a bytes-like object is required, not 'str'
修改后的代码:
from socket import *
serverName = 'host'
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()

suchocolate 发表于 2021-11-10 17:51:29

hhhljy 发表于 2021-11-10 14:44
我第一次也是这样写的,会提示要使用bytes的格式
我查了,在python2里面是不分bytes和str的,在python3 ...

message = message.encode()这句没了?

hhhljy 发表于 2021-11-11 13:04:47

suchocolate 发表于 2021-11-10 17:51
message = message.encode()这句没了?

加上之后可以了,感谢感谢,原来只要message转码,学到了,谢谢
页: [1]
查看完整版本: python 使用socket .sendto的问题