TypeError:需要一个类似字节的对象,而不是“str”套接字编程

Posted

技术标签:

【中文标题】TypeError:需要一个类似字节的对象,而不是“str”套接字编程【英文标题】:TypeError: a bytes-like object is required, not 'str' socket programming 【发布时间】:2021-10-28 14:32:07 【问题描述】:

我已经从一个使用服务器客户端的问答游戏的 github 下载了这个项目,其中服务器需要连接两个客户端实例作为 player1 和 player2,但我遇到了一个小错误 player1 已成功连接,但在尝试连接播放器时2 报错请大神帮忙

client.py 代码

def question(s):
    ques = s.recv(1024)
    print (ques)
    ans = input("Answer: ")
    while ans not in ['A', 'B', 'C', 'D']:
        print ("Enter a valid choice!")
        ans = input("Answer: ")
    s.sendall(ans)
    response = s.recv(1024)
    print (response)

while True:
    choice = s.recv(1024)
    if choice[0] == "Q":
        question(s)
    elif choice[0] == "S":
        scores(s)
    elif choice[0] == "C":
        challenge(s)
    elif choice[0] == "X":
        final(s)
        break
    elif choice[0] == "A":
        final(s)
    else:
        print ("Invalid choice: ", choice)

server.py 代码

print ("Server bound to ", HOST, ":", PORT, "\nConnect both players before continuing...")
(conn1, addr) = s.accept()
print ("Connected to Player 1 at ", addr)
(conn2, addr) = s.accept()
connlist = [conn1, conn2]
conn1.sendall("A\n")   //line 47
time.sleep(0.1)
conn1.sendall("You are Player 1\n")
time.sleep(0.1)
conn2.sendall("A\n")
time.sleep(0.1)
conn2.sendall("You are Player 2\n")
time.sleep(0.1)
print ("Connected to Player 2 at ", addr)
for questionNo in range(totalQuestions):
    conn1.sendall("A\n")
    time.sleep(0.1)
    conn1.sendall("Question Number "+str(questionNo+1)+" for Player "+str(questionNo%2+1)+"\n")
    time.sleep(0.1)
    conn2.sendall("A\n")
    time.sleep(0.1)
    conn2.sendall("Question Number "+str(questionNo+1)+" for Player "+str(questionNo%2+1)+"\n")
    time.sleep(0.1)

我得到的错误是: 服务器端

$ python3 server.py
Enter the port number to bind with: 8888
Enter the total number of questions: 5
Enter the name of the quiz file: ques.txt
Server bound to  localhost : 8888 
Connect both players before continuing...
Connected to Player 1 at  ('127.0.0.1', 56912)
Traceback (most recent call last):
  File "server.py", line 47, in <module>
    conn1.sendall("A\n")
TypeError: a bytes-like object is required, not 'str'

客户端:

$ python3 client.py
Enter the port number to which the server is bound: 8888
Traceback (most recent call last):
  File "client.py", line 39, in <module>
    if choice[0] == "Q":
IndexError: index out of range

【问题讨论】:

代码是为python 2写的吗?尝试将conn1.sendall("A\n") 替换为conn1.sendall(bytes("A\n", "utf-8")) sendall(b'A\n') 会简单很多。 这能回答你的问题吗? TypeError: a bytes-like object is required, not 'str' 【参考方案1】:

通过套接字进行通信时,您需要以表单字节而不是字符串格式发送数据

server.py 中,将所有 conn.sendall() 实例替换为

conn.sendall(message.encode()) #encode method converts str to bytes

类似地,在 client.py 中,您可能希望使用接收数据的字符串格式而不是原始字节来运行

ques = s.recv(1024).decode()  # .decode() converts bytes to str

您可以阅读有关编码和解码的更多信息here

【讨论】:

以上是关于TypeError:需要一个类似字节的对象,而不是“str”套接字编程的主要内容,如果未能解决你的问题,请参考以下文章

“TypeError:在 OAuth 2.0 回调请求期间需要一个类似字节的对象,而不是 'str'”

诱变剂:TypeError:需要一个类似字节的对象,而不是“str”

TypeError:需要一个类似字节的对象,而不是“str”套接字编程

Django Rest Framework TypeError需要一个类似字节的对象,而不是'str'

TypeError:需要一个类似字节的对象,而不是使用 pickle 加载时的“str”

TypeError:在尝试发送 http 请求时需要一个类似字节的对象,而不是“str”