| 1 |
import eventlet |
| 2 |
import sys |
| 3 |
from eventlet.green import socket, zmq |
| 4 |
from eventlet.hubs import use_hub |
| 5 |
use_hub('zeromq') |
| 6 |
|
| 7 |
ADDR = 'ipc:///tmp/chat' |
| 8 |
|
| 9 |
ctx = zmq.Context() |
| 10 |
|
| 11 |
|
| 12 |
def publish(writer): |
| 13 |
|
| 14 |
print("connected") |
| 15 |
socket = ctx.socket(zmq.SUB) |
| 16 |
|
| 17 |
socket.setsockopt(zmq.SUBSCRIBE, "") |
| 18 |
socket.connect(ADDR) |
| 19 |
eventlet.sleep(0.1) |
| 20 |
|
| 21 |
while True: |
| 22 |
msg = socket.recv_pyobj() |
| 23 |
str_msg = "%s: %s" % msg |
| 24 |
writer.write(str_msg) |
| 25 |
writer.flush() |
| 26 |
|
| 27 |
|
| 28 |
PORT = 3001 |
| 29 |
|
| 30 |
|
| 31 |
def read_chat_forever(reader, pub_socket): |
| 32 |
|
| 33 |
line = reader.readline() |
| 34 |
who = 'someone' |
| 35 |
while line: |
| 36 |
print("Chat:", line.strip()) |
| 37 |
if line.startswith('name:'): |
| 38 |
who = line.split(':')[-1].strip() |
| 39 |
|
| 40 |
try: |
| 41 |
pub_socket.send_pyobj((who, line)) |
| 42 |
except OSError as e: |
| 43 |
# ignore broken pipes, they just mean the participant |
| 44 |
# closed its connection already |
| 45 |
if e[0] != 32: |
| 46 |
raise |
| 47 |
line = reader.readline() |
| 48 |
print("Participant left chat.") |
| 49 |
|
| 50 |
try: |
| 51 |
print("ChatServer starting up on port %s" % PORT) |
| 52 |
server = eventlet.listen(('0.0.0.0', PORT)) |
| 53 |
pub_socket = ctx.socket(zmq.PUB) |
| 54 |
pub_socket.bind(ADDR) |
| 55 |
eventlet.spawn_n(publish, |
| 56 |
sys.stdout) |
| 57 |
while True: |
| 58 |
new_connection, address = server.accept() |
| 59 |
|
| 60 |
print("Participant joined chat.") |
| 61 |
eventlet.spawn_n(publish, |
| 62 |
new_connection.makefile('w')) |
| 63 |
eventlet.spawn_n(read_chat_forever, |
| 64 |
new_connection.makefile('r'), |
| 65 |
pub_socket) |
| 66 |
except (KeyboardInterrupt, SystemExit): |
| 67 |
print("ChatServer exiting.") |