用udp写的小型简单的聊天室模型,才学的,大神不要笑话
给象我一样的萌新看的,多进程我写不出同时收发信息,我用多线程写的服务端:
程序代码:
from socket import * import os,sys from threading import Thread """ UDP服务端 协议: L:登陆 C:聊天 Q:退出 """ ADDR = ('0.0.0.0',8888) # 服务端地址和端口 user = {} # 存储用户信息 no_word = ['你妈','你玛'] no_user = {} no_chart = [] s = socket(AF_INET,SOCK_DGRAM) s.bind(ADDR) def do_login(name,addr) : # 登陆 # print(name,user) if name in user: s.sendto(("用户名'%s'已存在,请换一个名字"%name).encode(),addr) return s.sendto(b'OK',addr) # 可以进入聊天室 # 先通知其它人,再存储该名字 msg = "C `系统信息:欢迎'%s'进入聊天室"%name for i in user: s.sendto(msg.encode(),user[i]) user[name] = addr # print(user) def do_chart(name,msg): # 聊天 # print(name,msg) if name in no_user: if no_user[name] > 4: s.sendto(('C `系统提示:由于你多次发送不文明言语,你已经被禁言!').encode(),user[name]) return msg = is_not_word(name,msg) # print(msg) for key,addr in user.items(): if key != name: # print(key,addr) s.sendto(('C `'+name+' 说:'+msg).encode(),addr) return def do_quit(name): # 退出 msg = "C `系统信息:'%s'已退出聊天室"%name for i in user: s.sendto(msg.encode(),user[i]) user.pop(name) # print(user) return def do_request(s): while True: data,addr = s.recvfrom(1024) tmp = data.decode().split(' ') # print('收到信息:',data.decode()) if tmp[0] == 'L': # 登陆 do_login(tmp[1],addr) elif tmp[0] == 'C': # 聊天 do_chart(tmp[1],tmp[2]) elif tmp[0] == 'Q': # 退出 do_quit(tmp[1]) def main(): # 处理请求 p_msg = Thread(target=to_msg) p_msg.start() do_request(s) def to_msg(): while True: msg = input() for i in user: s.sendto(("C `系统信息:"+msg).encode(),user[i]) def is_not_word(name,msg): for i in no_word: if i in msg: is_not_user(name) msg = msg.replace(i,'*') # print(msg) return msg def is_not_user(name): if name not in no_user: no_user[name] = 1 else: no_user[name] += 1 print('被禁言用户列表:',no_user) if __name__ == '__main__': main()
客户端
程序代码:
from socket import * import os,sys from threading import Thread """ UDP客户端 协议: L:登陆 C:聊天 Q:退出 """ ADDR = ('127.0.0.1',8888) s = socket(AF_INET,SOCK_DGRAM) def main(): name = to_login() p_recv = Thread(target=to_recv) p_recv.start() # to_recv() to_send(name) print('退出聊天室,程序结束') sys.exit() def to_login(): while True: name = input('请输入姓名>>') msg = 'L ' + name s.sendto(msg.encode(),ADDR) data,addr = s.recvfrom(128) print('收到信息:',data.decode()) if data.decode() == 'OK': print('你已经入进聊天室',) return name else: print(data.decode()) def to_recv(): while True: data = s.recv(1024) print(data.decode()) tmp = data.decode().split(' `') print(tmp[1]) def to_send(name): while True: msg = input() if msg == 'q': msg = 'Q '+name s.sendto(msg.encode(),ADDR) sys.exit() else: msg = 'C '+name+' '+ msg s.sendto(msg.encode(),ADDR) if __name__ == '__main__': main()