You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB
Python

from gevent import monkey, spawn
monkey.patch_all()
# 引入协程库并替换python的各种内部实现
from socket import *
from typing import *
# 当前连接
conns: Set[Tuple[socket, Any]] = set()
# 将消息发至所有客户端
def boardcast(message: str):
print(message)
for conn, addr in conns:
print('send to ', conn, addr)
conn.send(message.encode())
# 处理一个新的传入连接
def process_connection(conn: socket, addr):
conns.add((conn, addr))
boardcast('server:global:{} connected.'.format(addr))
while True:
try:
res_raw = conn.recv(1 << 20)
if not res_raw:
raise
except Exception:
# 异常处理:移除当前连接并通知剩余用户
conns.remove((conn, addr))
boardcast('server:global:{} disconnected.'.format(addr))
return
res = res_raw.decode()
boardcast('{}:{}'.format(addr, res))
if __name__ == "__main__":
with socket(AF_INET, SOCK_STREAM) as s:
s.bind(('0.0.0.0', 34567))
s.listen(1 << 16)
while True:
conn, addr = s.accept()
# 启动一个新的协程来处理连接
spawn(process_connection, conn, addr)