微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python套接字错误TypeError:需要一个类似字节的对象,而不是'int'

如何解决Python套接字错误TypeError:需要一个类似字节的对象,而不是'int'

我正在尝试创建一个服务器,该服务器将从客户端接收消息并正确答复它们。 当我要求一个随机数(RAND)时,出现此错误“需要一个类似字节的对象,而不是'int'”, 我该如何解决

和另一个问题,我试图更改“ recv”功能中的字节,但未成功。有人可以帮我吗?:

import socket
import time
import random

server_socket = socket.socket()
server_socket.bind(('0.0.0.0',8820))
server_socket.listen(1)
(client_socket,client_address) = server_socket.accept()
localtime = time.asctime( time.localtime(time.time()) )
ran = random.randint(0,10)
RUN = True
recieve = 1024

while RUN:
    client_input = (client_socket.recv(recieve)).decode('utf8')
    print(client_input)
    if client_input == 'TIME':
        client_socket.send(localtime.encode())
    elif client_input == 'RECV':
        recieve = client_socket.send(input("the current recieve amount is " + int(recieve) + ". Enter the recieve amount: "))
    elif client_input == 'NAME':
        client_socket.send(str("my name is SERVER").encode())
    elif client_input == 'RAND':
        client_socket.send(ran.encode())
    elif client_input == 'EXIT':
        RUN = False
    else:
        client_socket.send(str("I can only get 'TIME','NAME','RAND','EXIT'").encode())
client_socket.close()
server_socket.close()

解决方法

客户代码为:

import socket

my_socket = socket.socket()
my_socket.connect(('127.0.0.1',8820))
while True:
    user_input = input("Naor: ")
    my_socket.send(user_input.encode())
    data = my_socket.recv(1024)
    print("Server: " + data.decode('utf8'))
my_socket.close()
,

此错误的原因是在Python 3中,字符串是Unicode,但是在网络上传输时,数据需要改为字节。所以...一些建议:

建议使用client_socket.sendall()而不是client_socket.send()来防止可能的问题,即您可能没有通过一次呼叫就发送了整个msg(请参阅文档)。 对于文字,为字节字符串添加“ b”:client_socket.sendallsend(str(“我只能获得'TIME','NAME','RAND','EXIT'”)。encode()) 对于变量,您需要将Unicode字符串编码为字节字符串(请参见下文)

    output = 'connection has been processed'
client_socket.sendall(output.encode('utf-8'))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。