在崩溃后重新连接到套接字

时间:2017-02-15 06:37:44

标签: python sockets

我的代码运行良好,但如果在工作过程中出现任何错误,则所有脚本都会崩溃,并且在我手动重新运行之前不会从套接字端口收到任何其他请求...

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
import threading
import glob
import requests

HOST = 'xxx.xxx.xxx.xxx'
PORT = 5050 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
try:
    s.bind((HOST, PORT))
except socket.error as mssg:
    print ('Bind failed. Error Code : ' + str(mssg[0]) + ' Message ' + mssg[1])
    sys.exit()
print ('Socket bind complete')
s.listen(10)
print ('Socket now listening')
def clientthread(conn,addrr):
        while True:
                data = conn.recv(1024)
                rcv_data = data.decode("utf-8").strip()
                if(len(rcv_data) != 0):
                        print(data)
                        reply =b"111\n\r"
                        r = requests.post("http://domain.comw.php?action=u&d="+rcv_data, data = {'act': rcv_data})
                        conn.send(reply)
                else:
                        print('errr')
                        break
while True:
    conn, addr = s.accept()
    print ('Connected with ' + addr[0] + ':' + str(addr[1]))
    t = threading.Thread(target=clientthread ,args=(conn,addr,))
    t.daemon=True
    t.start()
s.close()

如何在发生意外错误后自动重新绑定套接字?!

其他愚蠢的事情是在崩溃或关闭程序与控制+ c后在linux中由于socket in use错误而无法重新运行约4-5分钟!!

2 个答案:

答案 0 :(得分:2)

这样的东西
while True:
    try:
        # open socket and do your stuff
    except Exception as e:
        # log
        # close socket
        # maybe sleep a couple of seconds

答案 1 :(得分:1)

任何套接字意外崩溃后

操作系统保持状态,以避免任何数据丢失

所以你必须尽快告诉os释放端口以尝试重新连接

.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)