-
Notifications
You must be signed in to change notification settings - Fork 20
/
server.py
25 lines (19 loc) · 821 Bytes
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import usocket as socket
import uselect as select
class Server:
def __init__(self, poller, port, sock_type, name):
self.name = name
# create socket with correct type: stream (TCP) or datagram (UDP)
self.sock = socket.socket(socket.AF_INET, sock_type)
# register to get event updates for this socket
self.poller = poller
self.poller.register(self.sock, select.POLLIN)
addr = socket.getaddrinfo("0.0.0.0", port)[0][-1]
# allow new requests while still sending last response
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(addr)
print(self.name, "listening on", addr)
def stop(self, poller):
poller.unregister(self.sock)
self.sock.close()
print(self.name, "stopped")