Welcome, guest | Sign In | My Account | Store | Cart

The code is a barebones example of how to write a loop for a server so that it gracefully detects when the client has dropped the connection and goes back to listening for a new client.

Python, 41 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Server code ------------------------------
from multiprocessing.connection import Listener
import time

address = ''
port = 6000
authkey = 'test'

keep_running = True
while keep_running:
  print 'Waiting for client'
  listener = Listener((address, port), authkey=authkey) 
  remote_conn = listener.accept()
  print 'Got client ' + listener.last_accepted[0] + ':%d' %(listener.last_accepted[1])

  try:
    while True:
      if remote_conn.poll():
        msg = remote_conn.recv()
        print 'msg: ' + msg
        if msg=='quit':
          keep_running = False
          break
      else:
        time.sleep(0.01)
  except EOFError:
    print 'Lost connection to client'
    listener.close()

## Client code ----------------------------------
from multiprocessing.connection import Client

address = ('', 6000)
conn = Client(address, authkey='test')
    
keep_running = True
while keep_running:
  msg=raw_input('Enter string ')
  conn.send(msg)
  if msg=='quit':
    keep_running = False