You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Socket双人问答游戏运行TypeError与IndexError报错求助

问答游戏项目报错修复方案

错误根因

两个报错存在直接关联:

  • 服务端TypeError是因为Python3的socket通信接口要求发送数据为字节类型,代码直接传入字符串参数触发类型错误,服务端运行到第47行就直接崩溃退出
  • 客户端IndexError是因为服务端崩溃后主动断开了连接,客户端的recv()方法返回空字节串,访问索引[0]时触发越界错误

修复步骤

服务端修改

所有调用sendall()的位置,将字符串参数编码为utf-8格式的字节,示例修改如下:
原代码:

conn1.sendall("A\n")
conn1.sendall("You are Player 1\n")

修改后:

conn1.sendall("A\n".encode('utf-8'))
conn1.sendall("You are Player 1\n".encode('utf-8'))

所有发送字符串的位置都要按此规则调整,包括后续循环中发送问题提示的所有sendall调用。

客户端修改

需要补充字节和字符串的转换逻辑,同时增加空数据校验:

  1. 调整主循环接收逻辑,增加空数据判断和字节解码:
while True:
    choice = s.recv(1024)
    # 收到空数据代表服务端已断开连接,直接退出
    if not choice:
        print("与服务端连接中断,程序退出")
        break
    # 字节转字符串
    choice = choice.decode('utf-8')
    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)
  1. 调整question函数的收发逻辑,同步加解码/编码处理:
def question(s):
    # 接收内容解码为字符串
    ques = s.recv(1024).decode('utf-8')
    print (ques)
    ans = input("Answer: ")
    while ans not in ['A', 'B', 'C', 'D']:
        print ("Enter a valid choice!")
        ans = input("Answer: ")
    # 发送内容编码为字节
    s.sendall(ans.encode('utf-8'))
    # 接收内容解码为字符串
    response = s.recv(1024).decode('utf-8')
    print (response)
  1. 其余涉及socket收发的函数如scores、challenge、final,都要按照同样的规则调整:接收数据后调用decode('utf-8')转字符串,发送数据前调用encode('utf-8')转字节。

内容的提问来源于stack exchange,提问作者sanket kesarwani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:45:03