3
关闭连接套接字我有简单的函数,像一个客户。它发送一个事件消息并等待一个确认(为简单起见,我删除了该部分)。之后,它会得到接收更多的消息:防止在Python中
def send_data(message):
"""Connect to server and get requests"""
sock = socket.socket()
host = 'localhost'
port = 8000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))
try:
if message:
sock.sendall(message)
# Look for the response
has_request = False
while not has_request:
data = sock.recv(1024)
#First I get ACK, code not listed here...
#Next iteration, I got my request message
has_request = True
finally:
print >> sys.stderr, 'Closing socket'
sock.close()
return data
我称这种现象为__main__
声明:
if __name__ == '__main__':
server_data = send_data(event)
if server_data:
parse_request(server_data)
不过,我需要防止插座被自动关闭。因为我在分析请求后必须发送另一个消息。我删除了sock.close(),但套接字仍然关闭。这是因为我在回应数据,而且我不在函数范围内?
我只是想连接,然后接收和发送的消息没有任何问题,我在程序的任何时间。
那么这是一个更好的方法来返回套接字和socket.recv和socket.sendall在其他函数? – 2012-07-25 13:48:46
@FatihArslan:也许是更好的方法是把插座管理的对象/功能将创建插座,然后把它交给谁需要这个插槽:) – 2012-07-25 13:52:18
@FatihArslan:我编辑我的答案用这种方法 – 2012-07-25 13:55:21