forked from seven-liu/python_study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect_echo_server.py
79 lines (61 loc) · 1.87 KB
/
select_echo_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
#encoding:utf-8
import select
import socket
import sys
import Queue
#create TCP/IP socket
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setblocking(0)
#bind the socket to the port
server_address=('localhost',10000)
print >>sys.stderr,'starting up on %s port %s' %server_address
server.bind(server_address)
#listen for coming connection
server.listen(5)
#socket from which we expect to read
inputs=[server]
#socket to which we expect to write
outputs=[]
message_queues=[]
while inputs:
print >>sys.stderr,'waiting for the next event'
readable,writable,exceptional=select.select(inputs,outputs,inputs)
#handle inputs
for s in readable:
if s is server:
connection,client_address=s.accept()
print >>sys.stderr,'connection from',client_address
connection.setblocking(0)
inputs.append(connection)
message_queues[connection]=Queue.Queue()
else:
data=s.recv(1024)
if data:
print >>sys.stderr,'received "%s" from %s' %(data,s.getpeername())
message_queues[s].put(data)
if s not in outputs:
outputs.append(s)
else:
print >>sys.stderr,'closing',client_address
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]
#handle outputs
for s in writable:
try:
next_msg=message_queues[s].get_nowait()
except Queue.Empty:
print >>sys.stderr,'',s.getpeername(),'queue empty'
outputs.remove(s)
else:
print >>sys.stderr,'sending "%s" to %s' %(next_msg,s.getpeername())
s.send(next_msg)
#handle exceptions
for s in exceptional:
print >>sys.stderr,'exception condition on',s.getpeername()
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]