-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythonAsyncServer
92 lines (67 loc) · 2.15 KB
/
pythonAsyncServer
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import select
import socket
SERVER_ADDRESS = ('localhost', 8686)
MAX_CONNECTIONS = 10
INPUTS = list()
OUTPUTS = list()
def get_non_blocking_server_socket():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind(SERVER_ADDRESS)
server.listen(MAX_CONNECTIONS)
return server
def handle_readables(readables, server):
"""
Processing outs
"""
print('Handling R')
for resource in readables:
if resource is server:
print('Will append')
connection, client_address = resource.accept()
connection.setblocking(0)
INPUTS.append(connection)
print("new connection from {address}".format(address=client_address))
else:
data = ""
try:
data = resource.recv(1024)
except ConnectionResetError:
pass
if data:
print("getting data")
if resource not in OUTPUTS:
OUTPUTS.append(resource)
else:
clear_resource(resource)
def clear_resource(resource):
"""
Clear resource
"""
print('Clear R')
if resource in OUTPUTS:
OUTPUTS.remove(resource)
if resource in INPUTS:
INPUTS.remove(resource)
resource.close()
print('closing connection ' + str(resource))
def handle_writables(writables):
print('Handling W')
for resource in writables:
try:
resource.send(bytes('Hello from server!'))
except OSError:
clear_resource(resource)
if __name__ == '__main__':
server_socket = get_non_blocking_server_socket()
INPUTS.append(server_socket)
print("server is running, please, press ctrl+c to stop")
try:
while INPUTS:
print('IN WHILE, INPUT AMOUNT ' + str(len(INPUTS)))
readables, writables, exceptional = select.select(INPUTS, OUTPUTS, INPUTS)
handle_readables(readables, server_socket)
handle_writables(writables)
except KeyboardInterrupt:
clear_resource(server_socket)
print("Server stopped! Thank you for using!")