Page MenuHomec4science

gol.py
No OneTemporary

File Metadata

Created
Thu, Jun 6, 03:35
#!/usr/bin/env python3
"""
Example of a simple TCP server that is written in (mostly) coroutine
style and uses asyncio.streams.start_server() and
asyncio.streams.open_connection().
Note that running this example starts both the TCP server and client
in the same process. It listens on port 12345 on 127.0.0.1, so it will
fail if this port is currently in use.
"""
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
import socket
import struct
import threading
import socketserver
ax = plt.gca()
plt.ion()
data = np.empty((1080,1920), dtype=np.uint8)
img = ax.imshow(data)
plt.show()
nb_parts = 0
nb_parts_lock = threading.Lock()
def redraw():
img.set_data(data)
plt.draw()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
local_data = threading.local()
unpacker = struct.Struct('I I I I I I I')
rdata = self.request.recv(unpacker.size, socket.MSG_WAITALL)
prank, psize, fh, fl, y, x, ghost = unpacker.unpack(rdata)
rdata = np.empty((fh, fl), dtype = np.uint8)
h = fh - 2 * ghost
l = fl - 2 * ghost
cur_thread = threading.current_thread()
print("Rank {0}/{6} ({5}) connected, grid({1}x{2}) + {3}x{4}".format(
prank, h, l, y, x, cur_thread.name, psize))
while True:
global data
self.request.recv_into(rdata,
rdata.size,
socket.MSG_WAITALL)
data[y:y + h, x:x + l] = rdata[ghost : -ghost, ghost : -ghost]
with nb_parts_lock:
global nb_parts
nb_parts += 1
if nb_parts == psize:
redraw()
nb_parts = 0
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "0.0.0.0", 4321
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
try:
server_thread.join()
finally:
server.shutdown()
server.server_close()

Event Timeline