import socket
import threading
import queue
import json
class Server(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
self.address = ('', port)
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def recv_(self, data, addr):
lock.acquire()
try:
que.put((addr, data))
finally:
lock.release()
def send_data(self):
while True:
if not que.empty():
data = ''
message = que.get()
if isinstance(message[1], str):
for i in range(len(users)):
for j in range(len(users)):
if message[0] == users[j][2]:
data = f'{users[j][1]}:{message[1]}'
break
users[i][0].send(data.encode())
if isinstance(message[1], list):
data = json.dumps(message[1])
for i in range(len(users)):
try:
users[i][0].send(data.encode())
except: pass
def tcp_connect(self, conn, addr):
users.append((conn, conn.recv(1024).decode(), addr))
self.recv_([users[i][1] for i in range(len(users))], addr)
try:
while True:
self.recv_(conn.recv(1024).decode(), addr)
except:
a = 0
for i in users:
if i[0] == conn:
users.pop(a)
self.recv_([users[i][1] for i in range(len(users))], addr)
break
a += 1
conn.close()
def run(self):
self.s.bind(self.address)
self.s.listen(5)
threading.Thread(target=self.send_data).start()
while True:
conn, addr = self.s.accept()
threading.Thread(target=self.tcp_connect, args=(conn, addr)).start()
users = []
que = queue.Queue()
lock = threading.Lock()
Server(1224).start()
可以自己用源码搭建,也可以下载文件用现成的。
© 版权声明
THE END
暂无评论内容