1

我有两个按钮。连接和断开连接。当第一次按下连接时,客户端成功连接到服务器(localhost:4106),当按下断开连接时,客户端断开连接。我的问题是,当我再次按“连接”时,客户端将不会重新连接到服务器,并且我收到一条错误消息:http: //i.imgur.com/dkvos.png

我认为这是因为套接字连接不能被重用?有解决方法吗?谢谢

#!/usr/bin/python          

import socket               
import Tkinter
import tkMessageBox

top = Tkinter.Tk()

s = socket.socket()       
host = '127.0.0.1' 
port = 4106              

def connect():
    s.connect((host, port))

def disconnect():
    s.close()

ConnectBtn = Tkinter.Button(top, text ="Connect", command = connect)

DisconnectBtn = Tkinter.Button(top, text ="Disconnect", command = disconnect)

ConnectBtn.pack()
DisconnectBtn.pack()

top.mainloop()
4

1 回答 1

-1

我不知道如何在 python 中重写此代码 tcl/tk,但可以作为解决方案的良好开端。这是 Scott Nichols 共享的代码。此代码显示了如果连接丢失,客户端将如何自动重新连接到服务器。

我成功使用此代码自动重新连接到服务器:

def open_connection():
    data0=''

    try:
        # Create a TCP/IP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Connect the socket to the port where the server is listening
        server_address = ('192.168.0.100', 8000)
        sock.settimeout(10)     # TimeOut 5 secunde

        while True:

            try:
                sock.connect(server_address)
                message = 'new connection'
                sock.sendall(message)

                # Look for the response
                amount_received = 0
                data0=sock.recv(1024)
                amount_received = len(data0)
                return

            finally:
                wNET = 0
                pass

    except:
        sock.close()
        time.sleep(60)
        del data0
于 2016-05-12T08:06:03.750 回答