Python-在多个函数中使用相同的套接字
我正在尝试跨多个函数使用python套接字,但我不确定如何使用。我得到一个错误:Python-在多个函数中使用相同的套接字,python,sockets,Python,Sockets,我正在尝试跨多个函数使用python套接字,但我不确定如何使用。我得到一个错误: Traceback (most recent call last): File "C:\Users\User\Desktop\PyBattle.py", line 169, in <module> client() File "C:\Users\User\Desktop\PyBattle.py", line 157, in client clientWait() File "
Traceback (most recent call last):
File "C:\Users\User\Desktop\PyBattle.py", line 169, in <module>
client()
File "C:\Users\User\Desktop\PyBattle.py", line 157, in client
clientWait()
File "C:\Users\User\Desktop\PyBattle.py", line 107, in clientWait
data = s.recv(BUFFER_SIZE)
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
以下是clientWait函数:
def client():
print "Enter server IP."
TCP_IP = raw_input(">")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
def clientWait():
os.system("cls")
print "Not your turn."
print "Username:" + username + " HP:" + str(hp) + " Level:" + str(level) + " Attack:" + str(attack) + " Defence:" + str(defence) + " Speed:" + str(speed)
print "Opponent:" + opponentUsername + " HP:" + str(opponentHp) + " Level:" + str(opponentLevel) + " Attack:" + str(opponentAttack) + " Defence:" + str(opponentDefence) + " Speed:" + str(opponentSpeed)
data = s.recv(BUFFER_SIZE)
clientProcess()
我相信这是因为插座不是全球性的?提前感谢您的帮助。您的错误不是特别的,因为套接字不是“全局的”。这是因为您在
clientWait
函数中引用的s
不是client
函数中的局部变量s
。您已经在其他地方创建了它(但没有告诉我们在哪里)
请不要将您的套接字设置为“全局”。只需从客户端
函数返回if,并将其传递到客户端等待
函数
您可能应该研究如何根据和利用大多数变量来重构代码。看起来你一直在使用全局变量,这会使你的程序变得脆弱、难以理解、难以测试、难以记录等等。事实证明,我所要做的就是在给它赋值之前将s声明为全局变量。因此:
global s
s = ...
再次感谢您提供的所有答案,并感谢Gerrat的帮助。查看我的代码后,我意识到我已经在client和clientWait函数之外创建了套接字。我将提供的pastebin链接的第4-7行演示了这一点。我已将它们注释掉,但遇到错误NameError:未定义全局名称。然而,我仍然不知道如何解决这个问题。完整代码如下: