python_udp_多人聊天室_简单版
udp-一定是client端先发送数据。
server.py
import socket
friend_lst = {'alex':'32','太白':'33'}
sk =socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',9001))
while True:
msg,addr = sk.recvfrom(1500)
msg = msg.decode('utf-8')
name,message = msg.split('|',1)
print('\033[1;%sm %s:%s\033[0m'%(friend_lst.get(name,'30'),name,message))
content = input('>>>')
sk.sendto(content.encode('utf-8'),addr)
# 补充知识:
# 1-字典的 dic.get(k,default_v)=v 方法: 如果k在字典中存在就返回它对应的v,如果不存在就返回一个设置的默认的default_v
# 2-print的字符串的颜色:EVA的微博
client_1.py
import socket
name = '太白'
# name = '大壮'
sk = socket.socket(type=socket.SOCK_DGRAM)
while True:
content = input('>>>')
if content.upper() == 'Q':
break
content = '%s|%s'%(name,content)
sk.sendto(content.encode('utf-8'),('127.0.0.1',9001))
msg = sk.recv(1024).decode('utf-8')
if msg.upper() == 'Q':
break
print(msg)
client_2.py
import socket
name = 'alex'
sk = socket.socket(type=socket.SOCK_DGRAM)
while True:
content = input('>>>')
if content.upper() == 'Q': break
content = '%s|%s'%(name,content)
sk.sendto(content.encode('utf-8'),('127.0.0.1',9001))
msg = sk.recv(1024).decode('utf-8')
if msg.upper() == 'Q': break
print(msg)