【发布时间】: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。我认为这是有道理的。