2

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 
4
  • shouldn't s = socket.socket() be s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)? Also, why do you need to restart the server? The client should be able to reconnect. Also, can you add the client software - perhaps that is the issue. Lastly, I believe that the os module is outdated - I may be wrong though (It does have its uses... I think ) Commented Feb 25, 2013 at 23:03
  • Consider using SocketServer.TCPServer. Commented Feb 25, 2013 at 23:04
  • Thank you @crayzeewulf, slowed my problem :) Commented Feb 25, 2013 at 23:28
  • @xxmbabanexx, the default parameters for socket.socket() are socket.AF_INET and socket.SOCK_STREAM so they can be left out. Commented Sep 7, 2013 at 21:19

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.