如何在不引起错误的情况下关闭TCP连接(客户端-服务器)

时间:2019-03-23 17:50:57

标签: python sockets

我有一个连接到服务器的GUI客户端。我尝试过创建允许客户端与服务器断开连接而不会引起错误的方法,但是我似乎无法使其正常工作。

我尝试使用shutdown方法,然后关闭socket.connection的方法。

# Client side (GUI)
def On_Close(self):  # When exit button is pressed on window
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        self.destroy()

def QUIT_Program(self):  # When the tk button widget 'QUIT' is pressed
    if messagebox.askyesno("QUIT","Are you sure want to quit?"):  # Ensures the user can't accidentally quit the program
        self.Data_Handler.Send_Q.put("QUIT")
        self.Conn.shutdown(0)
        self.Conn.close()
        self.QUIT = True
        self.destroy()
        time.sleep(10)
        sys.exit()

#Server side
if __name__ == "__main__":
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Sets up socket connection
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # Configures socket options, such as re-use of ports
    s.bind((HOST, PORT))
    # Binds preset Host and Port values
    s.listen(1)
    # Listens for connections
    while True:
        try:
            Conn, Addr = s.accept()  # Accepts connections
            connThread = Thread(target=Server, args=(Conn, Addr, DB_Conn, DB_Cursor))
            # Sets up thread for the 'Server' object
            connThread.start()
            # Begins the thread
        except Exception as err:
            Error_Report(err, "NAME=MAIN")

当按下退出按钮或我自己制作的退出小部件时,我希望服务器和客户端之间的TCP连接被关闭,而不会出现任何错误。

我实际上得到的是:

  

回溯(最近通话最近):   _bootstrap_inner中的第916行的文件“ C:\ Users \ Green \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ threading.py”       self.run()

     

文件“ C:\ Users \ Green \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ threading.py”,行864,正在运行       self._target(* self._args,** self._kwargs)

     

文件“ E:\ Python \ Py_Proj \ Project_Data_Handler_Class_v3.py”,第65行,在   Func_Receiver       数据= self.Get_Data(“ Func_Receiver”)

     

Get_Data中第60行的文件“ E:\ Python \ Py_Proj \ Project_Data_Handler_Class_v3.py”       Data_String = json.loads(self.master.Conn.recv(4096).decode())

     

ConnectionResetError:[WinError 10054]现有连接被远程主机强行关闭

0 个答案:

没有答案