【问题标题】:Python sockets error TypeError: a bytes-like object is required, not 'int'Python套接字错误TypeError:需要一个类似字节的对象,而不是'int'
【发布时间】:2020-08-17 20:00:55
【问题描述】:

我正在尝试创建一个服务器,该服务器将接收来自客户端的消息并正确回答它们。 当我要求一个随机数(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()

【问题讨论】:

    标签: python-3.x server atom-editor


    【解决方案1】:

    客户端代码是:

    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()
    

    【讨论】:

    • “复制粘贴此代码”的答案并不是真正的 HQ(高质量),最好解释一下,它是如何工作的以及为什么会这样。作为一个自我回答,我认为这还不错,但是写一些解释仍然是一种改进。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-16
      • 2019-07-10
      • 1970-01-01
      • 2021-10-28
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      相关资源
      最近更新 更多