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

2 回答 2

1

我不知道你是否找到了答案,但我在寻找同样的问题时发现了这个。我试图重置服务器上的套接字,以便我可以连接到下一个客户端,所以我尝试使用 socket.close() 然后重新初始化整个套接字,但实际上你不需要在服务器端做任何事情,只需在客户端使用 socket.close() ,另一个客户端就可以连接而不会搞砸服务器(我意识到这现在可能对你没有多大帮助,但万一其他人做了我想让他们知道的事情)

于 2013-09-07T20:55:14.017 回答
0

如果我得到你,你想在客户端断开连接时再次收听,所以这应该完成它的工作:

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
于 2020-07-02T13:50:11.217 回答