main.py 818 Bytes
Newer Older
Constantin's avatar
Constantin committed
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
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python3

import selectors
import socket

sel = selectors.DefaultSelector()

def accept(sock, mask):
	conn, addr = sock.accept()  # Should be ready
	print('accepted', conn, 'from', addr)
	conn.setblocking(False)
	sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
	data = conn.recv(1000)  # Should be ready
	if data:
		print('echoing', repr(data), 'to', conn)
		conn.send(data)  # Hope it won't block
		conn.send('Danke für Ihre Nachricht!'.encode("utf-8"))
	else:
		print('closing', conn)
		sel.unregister(conn)
		conn.close()

sock = socket.socket()
sock.bind(('localhost', 1234))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
	events = sel.select()
	for key, mask in events:
		callback = key.data
		callback(key.fileobj, mask)