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.
39 lines
1008 B
Python
39 lines
1008 B
Python
from gevent import monkey, spawn
|
|
monkey.patch_all()
|
|
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)
|