Debian Codegraph @

examples/chat_server.py

raw
1 import eventlet
2 from eventlet.green import socket
3
4 PORT = 3001
5 participants = set()
6
7
8 def read_chat_forever(writer, reader):
9 line = reader.readline()
10 while line:
11 print("Chat:", line.strip())
12 for p in participants:
13 try:
14 if p is not writer: # Don't echo
15 p.write(line)
16 p.flush()
17 except OSError as e:
18 # ignore broken pipes, they just mean the participant
19 # closed its connection already
20 if e[0] != 32:
21 raise
22 line = reader.readline()
23 participants.remove(writer)
24 print("Participant left chat.")
25
26 try:
27 print("ChatServer starting up on port %s" % PORT)
28 server = eventlet.listen(('0.0.0.0', PORT))
29 while True:
30 new_connection, address = server.accept()
31 print("Participant joined chat.")
32 new_writer = new_connection.makefile('w')
33 participants.add(new_writer)
34 eventlet.spawn_n(read_chat_forever,
35 new_writer,
36 new_connection.makefile('r'))
37 except (KeyboardInterrupt, SystemExit):
38 print("ChatServer exiting.")