peiman F.
peiman F.

Reputation: 1658

re connect to socket after crashe

My code is working good but if in working process any error raise all script will crash and dont receive any other request from socket port until i rerun it manually...

#!/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()

how can i auto rebind the socket after any unexpected error?!

also other stupid thing is in linux after crash or close program with control+c i cant re run it for about 4-5 minutes due to socket in use error !!

Upvotes: 1

Views: 170

Answers (2)

roozgar
roozgar

Reputation: 394

after any socket unexpectedly broke down

the os keep the status live for avoid any data lost

so you must tell the os free up port ASAP for try to reconnect

.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

Upvotes: 1

Pedru
Pedru

Reputation: 1460

Something like

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

Upvotes: 2

Related Questions