Python3.x套接字模块;类似字节的对象不是str“;

Python3.x套接字模块;类似字节的对象不是str“;,python,python-3.x,sockets,networking,tcp,Python,Python 3.x,Sockets,Networking,Tcp,我正在使用Python 3.5.1中预装的Socket模块制作一个简单的网络消息传递接口。代码返回一个 TypeError:需要类似字节的对象,而不是“str” 服务器接收到消息,但在此之后程序因该错误而崩溃^I已经做了研究,并且知道使用了.encode/.decode('utf-8'),但它仍然返回相同的错误。错误在tcpServer.py文件上,其源代码如下。我读过关于在这里使用b'string'的内容,但我不知道它是否适用于变量。先谢谢你 资料来源: import socket def

我正在使用Python 3.5.1中预装的Socket模块制作一个简单的网络消息传递接口。代码返回一个

TypeError:需要类似字节的对象,而不是“str”

服务器接收到消息,但在此之后程序因该错误而崩溃^I已经做了研究,并且知道使用了.encode/.decode('utf-8'),但它仍然返回相同的错误。错误在tcpServer.py文件上,其源代码如下。我读过关于在这里使用b'string'的内容,但我不知道它是否适用于变量。先谢谢你

资料来源:

import socket

def Main():
    host = "127.0.0.1"    #makes localhost the host server
    port = 5000           #any random port between 1024 and 65535

    s = socket.socket()   #creates a new socket object
    s.bind((host, port))

    s.listen(1)           #listens for 1 connection

    c, addr = s.accept() #accepts a connection and address

    print("Connection from: ", str(addr))
    while True:
        data = c.recv(1024) #receives bytes from connection with a 1024 buffer
        if not data:
            break
        print("From Client: ",str(data.decode()))
        data = str(data).upper() #overwrites current values in var data with a string of the new data in uppercase
        print("Sending: ",str(data))
        c.send(data) #tells connection to send the data
    c.close()

if __name__ == "__main__":
    Main()

当遇到异常时,Python提供了一个有启发性的回溯,请在问题主体中提供该回溯。
data=data.upper()
而不是
data=str(data.upper()
。如果需要字节,则无需将字节转换为字符串。
str(data).upper()返回发送前需要编码的
str
。如前所述,在您的案例中根本不需要转换字节。谢谢dietrich和tdelaney,它现在可以工作了!