我正在尝试创建一个客户端/服务器控制台游戏,但我无法保持套接字处于活动状态,它似乎在我打电话之前就关闭了,close()
我不知道为什么。
我已经阅读了这里的线程,但是我已经在 while 循环之外调用connect()
了,因为在我尝试运行它之前,它的逻辑对我来说已经有意义了,但是我仍然从服务器 shell 收到错误:
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
到目前为止,我在客户端 shell 上没有收到错误,它只是在启动后立即退出运行,这也是发生服务器错误的时候。
在修复了注释中指出的错误之后,客户端现在还显示一个错误,指出connected
在尝试启动 while 循环时未定义,但应该Connect()
在进入应该设置connected = True
的循环之前运行,因此循环应该运行但没有。我怀疑这根本与服务器问题有关,但这里的问题可能是什么?
我将把两者的代码放在下面:
客户
import socket
def GetData():
data = s.recv(1000).decode()
if (data == "closing"):
connected = False
else:
print(data)
def SendData():
tdata = input("")
s.send(data.encode())
def Connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 2222))
connected = True
global connected
Connect()
while (connected == True):
GetData()
if (connected == False):
s.close()
break
SendData()
服务器
import socket
import random
def TheMainGame():
print ("started TheMainGame") # Remove after debug
def within(val, goal):
print ("Runing 'within' function") # Remove after debug
i = abs(val - goal)
if (i <= 5):
return True
else:
return False
def Guess():
print ("Running 'Guess' function") # Remove after debug
while True:
print ("Entered while loop") # Remove after debug
data = "What is your guess?"
c.send(data.encode())
print ("Sent data") # Remove after debug
t = c.recv(1000).decode()
print ("Got data") # Remove after debug
if (t == x):
data = "Correct!"
c.send(data.encode())
data = "closing"
c.send(data.encode())
c.close()
break
elif (within(t,x) == True):
data = "You're close!"
c.send(data.encode())
elif (within(t,x) == False):
data = "Try again"
c.send(data.encode())
else:
data = "There was an error computing the value"
c.send(data.encode())
c.close()
break
x = random.randrange(1, 20, 1)
Guess()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 2222))
s.listen(5)
global data
while True:
(c,a) = s.accept()
print("Received connection from", a) # Remove after debug
data = "Hello %s" %a[0] # Remove after debug
c.send(data.encode()) # Remove after debug
TheMainGame()
服务器外壳中的错误与第 19 行有关,这就是服务器尝试向客户端询问问题的原因,这也是它第二次尝试向客户端发送数据但尝试从未成功发生,这就是为什么我认为即使在此之前我从未告诉它任何地方,套接字也被关闭,因为它甚至无法检查 if t == x
. 是什么导致套接字关闭?