-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
118 lines (96 loc) · 2.41 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env python
#server.py
import socket, traceback, time
from threading import *
def generatedata(index):
glb_condition.acquire()
glb_condition.wait()
glb_condition.release()
# TODO:
return data
def recvdata(address,port):
print 'The thread for receiving data is running.'
global glb_client_data
index=glb_client_address.index(address)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('',port))
while 1:
data=s.recvfrom(8192)[0]
glb_client_data[index]=data
def senddata(address,port):
print 'The thread for sending data is running.'
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect((address,51000))
index=glb_client_address(address)
while 1:
data=generatedata(index)
s.sendall(data)
def handlechild(clientsock):
global glb_client_name
global glb_client_data
global glb_client_address
address=clientsock.getpeername()[0]
port=10000+len(glb_client_address)
print 'Got connection from', address
# Save its information
glb_client_name.append('')
glb_client_data.append('')
glb_client_address.append(address)
t=Thread(target=recvdata,args=[address,port])
t.setDaemon(1)
t.start()
t=Thread(target=senddata,args=[address,port])
t.setDaemon(1)
t.start()
while 1:
# Send the client list, per 2 seconds.
data=','.join(glb_client_address)
try:
clientsock.sendall(data)
except:
traceback.print_exc()
continue
time.sleep(2)
clientsock.close()
def checkandorder():
# Only when all the clients' data are updated, will this function wake the other threads.
data=[]
while 1:
if data==glb_client_data:
continue
else:
glb_condition.acquire()
glb_condition.notifyAll()
glb_condition.release()
data=glb_client_data
host=''
port=51222
glb_client_name=[]
glb_client_data=[]
glb_client_address=[]
glb_condition=Condition()
print 'Initialize server...'
# Set up a socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(3)
# Start a new thread to synchronize other threads
t=Thread(target=checkandorder)
t.setDaemon(1)
t.start()
print 'Done.'
while 1:
try:
print 'Waiting for the clients...'
clientsock, clientaddr=s.accept()
print 'A client has been accepted.'
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue
# Start a new thread to handle it
t=Thread(target=handlechild, args=[clientsock], name=clientsock.getpeername()[0])
t.setDaemon(1)
t.start()
print 'Start a new thread for it.'