无法保持套接字活动 Python

Having trouble keeping socket alive Python

我正在尝试创建一个 client/server 主机游戏,但我无法让套接字保持活动状态,它似乎在我调用 close() 之前就关闭了,我可以'不知道为什么。

我已经阅读了线程 here,但是我在 while 循环之外调用了 connect(),因为在我尝试 运行 它之前,它的逻辑对我来说已经很有意义了,但我仍然从服务器 shell 收到错误消息:

ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

到目前为止,我在客户端 shell 上没有收到错误,它只是在 运行ning 启动后立即退出,这也是服务器发生错误的时候。
修复评论中指出的错误后,客户端现在还会显示一个错误,指出 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()

服务器中的错误shell与第19行有关,这就是服务器尝试向客户端询问问题的原因,这也是它第二次尝试向客户端发送数据,但从未尝试过成功发生,这就是为什么我认为套接字正在关闭,即使在那之前我从未告诉它任何地方,因为它甚至无法检查是否 t == x。是什么导致套接字关闭?

您在客户端误用了 global。

在正文中你有 global connected。这是不正确的。

相反,在文件的顶部放置:

import socket
connected = False

然后,在 Connect 函数中,拉入全局范围变量:

def Connect():
    global connected
    ...

关键字global是告诉函数使用全局范围内的变量,而不是定义它们。

注意: 您需要查看并解决此代码中的其他错误。

  1. 您在 server.py
  2. 中也做了同样的事情
  3. 您试图在 GetDataSendData 函数中引用套接字 s,但 s 仅在连接函数中是本地的(意味着连接函数存在后将下降。