Ryan Williams avatar Ryan Williams committed e1a226d

Updated chat server example to be resilient against broken pipes. Also used a set instead of a list and parameterized the port.

Comments (0)

Files changed (1)

examples/chat_server.py

 import eventlet
+from eventlet.green import socket
 
-participants = []
+PORT=3001
+participants = set()
 
 def read_chat_forever(writer, reader):
     line = reader.readline()
     while line:
         print "Chat:", line.strip()
         for p in participants:
-            if p is not writer: # Don't echo
-                p.write(line)
-                p.flush()
+            try:
+                if p is not writer: # Don't echo
+                    p.write(line)
+                    p.flush()
+            except socket.error, e:
+                # ignore broken pipes, they just mean the participant
+                # closed its connection already
+                if e[0] != 32:
+                    raise
         line = reader.readline()
     participants.remove(writer)
     print "Participant left chat."
 
 try:
-    print "ChatServer starting up on port 3000"
-    server = eventlet.listen(('0.0.0.0', 3000))
+    print "ChatServer starting up on port %s" % PORT
+    server = eventlet.listen(('0.0.0.0', PORT))
     while True:
         new_connection, address = server.accept()
         print "Participant joined chat."
         new_writer = new_connection.makefile('w')
-        participants.append(new_writer)
+        participants.add(new_writer)
         eventlet.spawn_n(read_chat_forever, 
                          new_writer, 
                          new_connection.makefile('r'))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.