【问题标题】:Python socket client unable to re-connectPython套接字客户端无法重新连接
【发布时间】:2016-05-12 16:49:31
【问题描述】:

我有两个按钮。连接和断开连接。当第一次按下连接时,客户端成功连接到服务器(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()

【问题讨论】:

  • 在 connect 中再次调用 socket.socket() 并将 s 分配给一个新的套接字。在关闭前检查 disconnect() 以确保它是有效的打开套接字。
  • 套接字不能重复使用;在connect()函数中使用s = socket.socket(),并将代码顶部s的声明替换为s = 0。您还可以使用disconnect() 函数仅在它是有效套接字时关闭套接字,方法是检查其值是否为0,并在成功断开连接后使该函数将其值设置为0。我认为这是有道理的。

标签: python sockets


【解决方案1】:

我不知道如何在 python 中重写此代码 tcl/tk,但可以作为解决方案的良好开端。 Here is the code shared by 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

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2013-04-21
    • 1970-01-01
    • 2021-12-22
    • 2013-02-14
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多