Discuss / Python / 简单的udp命令行群聊

简单的udp命令行群聊

Topic source

云端67395

#1 Created at ... [Delete] [Delete and Lock User]

服务端:

-- coding: utf-8 --

import socket import threading,time import re

user = []

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind(('192.168.1.105',9999)) print('Bind UDP on 9999...') while True: data,addr = s.recvfrom(1024) data = re.match(r'(\w+):([\w ]*)',data.decode('utf-8')).groups() if len(data) == 2: if data[1] == 'online': user.append((data[0],addr)) for n in user: s.sendto(b'%s online...' % data[0].encode('utf-8'),n[1]) print('Received from %s:%s.' % addr) continue print('Received from %s:%s.' % addr) for n in user: if n[0] != data[0]: s.sendto(bytes('>>>'+data[0]+':'+data[1],encoding = 'utf-8'),n[1])

客户端:

-- coding: utf-8 --

import socket import threading,time import re

def udpLink(sock,addr): while True: time.sleep(0.1) print(sock.recv(1024).decode('utf-8'))

print('input your sever ip:') while True: ip = input() if re.match(r'\d{3}.\d{3}.\d{1}.\d{3}',ip): break print('unlawful IP') print('input your name:') name = input() s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.sendto(bytes(name+':'+'online',encoding = 'utf-8'),(ip,9999)) t = threading.Thread(target = udpLink,args=(s,(ip,9999))) t.start() while True: data = input() s.sendto(bytes(name+':'+data,encoding = 'utf-8'),(ip,9999)) s.close()


  • 1

Reply