-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
85 lines (71 loc) · 1.79 KB
/
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
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
#!/usr/bin/env python
import select
import socket
import sys
import threading
class Server:
def __init__(self):
self.host = ''
self.port = 22000
self.backlog = 5
self.size = 1024
self.server = None
self.threads = []
def open_socket(self):
try:
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
except socket.error, (value,message):
if self.server:
self.server.close()
print "Could not open socket: " + message
sys.exit(1)
else:
print('opened server: {0}'.format(self.server.getsockname()))
def run(self):
print('server running')
self.open_socket()
input = [self.server, sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == self.server:
# handle the server socket
c = Client(self.server.accept())
c.start()
self.threads.append(c)
elif s == sys.stdin:
junk = sys.stdin.readline()
print('stdin: {0!r}'.format(junk))
# handle standard input
running = 0
# close all threads
self.server.close()
print('waiting for clients to quit...')
for c in self.threads:
c.join()
print('server closed')
class Client(threading.Thread):
def __init__(self,(client,address)):
threading.Thread.__init__(self)
self.client = client
self.address = address
self.size = 1024
def run(self):
running = 1
while running:
datastr = self.client.recv(self.size)
if datastr:
data = eval(datastr)
print('received: {0!r}'.format(data))
response = {'type':'start', 'accept':1}
# TODO: process data
self.client.send(str(response))
else:
self.client.close()
running = 0
if __name__ == "__main__":
s = Server()
s.run()