Skip to content

Instantly share code, notes, and snippets.

@c--y
Created April 14, 2014 17:39
Show Gist options
  • Select an option

  • Save c--y/10668345 to your computer and use it in GitHub Desktop.

Select an option

Save c--y/10668345 to your computer and use it in GitHub Desktop.
利用redis pub/sub机制实现的简单聊天工具
# coding=utf-8
import redis
import uuid
import sys
import threading
import os
HOST = '127.0.0.1'
DB = 1
rc = redis.Redis(HOST, db=DB)
# 频道名称
channel = 'chat:pub'
# 登录, 在session字典中注册一个用户名
def login(session):
nick_name = raw_input('Nickname:')
if not nick_name:
print 'error: type your nickname.'
sys.exit(-1)
session['user'] = nick_name
# 向公共频道发送一条消息
def say(session):
u = session['user']
if not u:
print 'error: user is none.'
sys.exit(-2)
body = raw_input('')
msg = u + ':' + body
rc.publish(channel, msg)
# 侦听公共频道
def listen():
sub = rc.pubsub()
sub.subscribe(channel)
for msg in sub.listen():
print msg['data']
# 交互循环
# 启动一个线程侦听频道
# 函数本身循环等待发送
def loop(session):
listen_thr = threading.Thread(target=listen)
listen_thr.start()
try:
while True:
say(session)
except KeyboardInterrupt, e:
print '\nexiting...'
os._exit(1)
# 启动
def app_run():
session = {}
login(session)
loop(session)
if __name__ == '__main__':
app_run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment