简体   繁体   中英

python socket server - listen even if client disconnects

This works fine

  #!/usr/bin/python
    import urllib
    import socket              
    import os
    s = socket.socket()         
    host = socket.gethostname() 
    port = 1514                
    s.bind((host, port))        

    s.listen(500)                 

    c, addr = s.accept()  
    while True:
          # Establish connection with client.
          print 'Got connection from', addr
          print c.recv(1024)
          c.send('Recieved') 

    c.close()                
    raw_input()

But a few things:

  1. When the client disconnects, the program closes. I want to make it so even if the client disconnects, the program will keep on listening for a new connection

  2. How can I make it wait infinitely for a connection?

You can just put a while True loop on the outside and try/except for the connection closing inside. In other words, accept() can be called in a loop.

However, the "right" way to do this is usually with an asynchronous/event-driven approach as is implemented by Python Twisted. That way you can accept connections from multiple clients concurrently, rather than having to wait for one connection to close before accepting the next one.

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