单机聊天室,直接python xxx.py 监听频道 订阅频道
键入over即可断开speak,双方都键入over,程序结束
from threading import Thread
import sys
import redis
conn = redis.Redis()
def listen(listen_channel):
p = conn.pubsub()
p.psubscribe(listen_channel)
for item in p.listen():
if item['type'] == 'pmessage':
data = item['data'].decode()
print(data)
if data == 'over':
break
def speak(speak_channel):
while True:
msg = input()
p = conn.publish(speak_channel, msg)
if msg == 'over':
break
if __name__ == '__main__':
listen_channel, speak_channel = sys.argv[1], sys.argv[2]
print(f'listen_channel:{listen_channel}\nspeak_channel:{speak_channel}')
worker = [Thread(target=listen, args=(listen_channel,)), Thread(target=speak, args=(speak_channel,))]
for i in worker:
i.start()