1 #服务端 2 from socket import * 3 import json 4 def recvMsg(s): 5 while True: 6 #接收用户的信息 7 data,address = s.recvfrom(1024) 8 data = json.loads(data) 9 print(data,address) 10 11 if data['type'] == 'enter': 12 # 将用户进入聊天室的信息发给其它所有在线用户 13 sendToAll(('>>系统:%s进入了聊天室'%data['content']).encode('utf-8'),s,address) 14 #将用户信息加入users字典 15 if address not in users:users[address]=data['content'] 16 elif data['type'] == 'quit': 17 # 将用户离开聊天室的信息发给其它所有在线用户 18 sendToAll(('>>系统:%s离开了聊天室' % data['content']).encode('utf-8'), s, address) 19 # 将退出的用户从users中删除 20 users.pop(address) 21 22 elif data['type'] == 'msg': 23 sendToAll(('>>%s:%s'%(users[address],data['content'])).encode('utf-8'),s,address) 24 25 else: 26 for i in users: 27 if users[i] == data['name']: 28 s.sendto(('>>%s私信你说:%s'%(users[address],data['content'])).encode('utf-8'),i) 29 30 def sendToAll(msg,s,address): 31 for addr in users: 32 if addr != address: 33 s.sendto(msg,addr) 34 35 36 def main(): 37 #创建socket 38 s = socket(AF_INET,SOCK_DGRAM) 39 #绑定服务器ip和端口 40 s.bind(('172.16.11.199',8888)) 41 #接收用户的信息 42 recvMsg(s) 43 #发送信息给用户 44 if __name__ == '__main__': 45 #设置一个全局的变量,保存所有进入聊天室的用户信息{'地址':'昵称','地址':'昵称',....} 46 users = {} 47 # print(users) 48 main() 49 50 51 52 #客户端 53 from socket import * 54 import json 55 from threading import Thread 56 def sendMsg(c,server): 57 while True: 58 msg = input("").strip() 59 #发送消息 60 if not msg: 61 continue 62 elif msg.lower() == 'quit': 63 # 发送进入聊天室的信息 64 msg = {'type': 'quit', 'content': username} 65 c.sendto(json.dumps(msg).encode('utf-8'), server) 66 break 67 #私聊 68 elif msg.startswith('@'): 69 name = str(msg[1:]) 70 msg2 = input('>>请输入你要对他说的话: ').strip() 71 msg3 = {'type':'msg2','content':msg2,'name':name} 72 print(">>我对%s说: %s"%(name ,msg2)) 73 c.sendto(json.dumps(msg3).encode('utf-8'),server) 74 else: 75 #正常信息 76 msg1 = {'type':'msg','content':msg} 77 print(">>我说:%s"%msg) 78 c.sendto(json.dumps(msg1).encode('utf-8'), server) 79 80 def recvMsg(c): 81 while True: 82 data,address = c.recvfrom(1024) 83 #打印出接收到的消息 84 print(data.decode('utf-8')) 85 86 def main(): 87 c = socket(AF_INET,SOCK_DGRAM) 88 #服务器的地址 89 server = ('172.16.11.199',8888) 90 #发送进入聊天室的信息 91 msg = {'type':'enter','content':username} 92 c.sendto(json.dumps(msg).encode('utf-8'),server) 93 #用户发送消息 94 t1 = Thread(target=sendMsg,args=(c,server)) 95 #用户接收消息 96 t2 = Thread(target=recvMsg,args=(c,)) 97 98 t1.start() 99 t2.start() 100 t1.join() 101 t2.join() 102 103 c.close() 104 if __name__ == '__main__': 105 #输入昵称 106 username = input('昵称:').strip() 107 print("%s,你已成功进入xx聊天室,想要退出请输入'quit'"%username) 108 main()