简体   繁体   中英

Restart socket server in python

I've wrote a simple socket server in python (OS X). I want the server to restart when a client terminate the communication, so that the client can do a reconnect to the server. Look at the code below, what do i have to do at the "lost contact" IF? I'm completely new to Python.

Here is the code:

import socket              
import os

s = socket.socket()       
host = socket.gethostname() 
port = 5555               


os.system('clear') 
print 'Server started'
print 'Waiting'

s.bind((host, port))       
s.listen(5)                 
c, addr = s.accept()     
print 'Contact', addr   
while True:
    msg = c.recv(1024)
    if not msg:
       s.close
       print "Lost contact"
       exit ()
    else: 
       print msg 

I dont know if you ever found your answer but i found this when i was searching for the same problem. I was trying to reset the socket on the server so that I could connect to the next client so i tried using socket.close() and then reinitializing the whole socket, but you actually don't need to do anything on the server side, just use socket.close() on the client side and another client can connect without screwing up the server (I realize this probably doesnt help you much now but in case anyone else did what i did I wanted them to know)

If I got you, you want to listen again when client gets disconnected so this should do its job:

import socket              
import os

s = socket.socket()       
host = socket.gethostname() 
port = 5555               


os.system('clear') 
print 'Server started'
print 'Waiting'

def server():
  s.bind((host, port))       
  s.listen(5)                 
  c, addr = s.accept()     
  print 'Contact', addr   
  while True:
      msg = c.recv(1024)
      if not msg:
         s.close
         print "Restarting..."
         server()
      else: 
         print msg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM