我正在使用Python 3.5.1中预装的套接字模块创建一个简单的网络消息传递接口。代码以
返回TypeError:需要类似字节的对象,而不是'str'
服务器收到消息,但之后程序因该错误而崩溃^我已经完成研究并且意识到使用.encode / .decode('utf-8')但它仍然返回相同的错误。错误发生在tcpServer.py文件中,其源代码如下所示。我已经读过在这里使用b'字符串',但我不知道它是否适用于变量。提前谢谢。
来源:
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()