new
This commit is contained in:
commit
262940bb44
79
server/yadyn
Normal file
79
server/yadyn
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
import select
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class DoneException(Exception): pass
|
||||||
|
|
||||||
|
class TimeoutException(Exception): pass
|
||||||
|
|
||||||
|
class Client(object):
|
||||||
|
def __init__(self, sock, address):
|
||||||
|
self.sock = sock
|
||||||
|
self.address = address
|
||||||
|
self.timestamp = int(time.time())
|
||||||
|
self.timeout = 5
|
||||||
|
|
||||||
|
def process(self):
|
||||||
|
self.timestamp = int(time.time())
|
||||||
|
data = self.sock.recv(8192)
|
||||||
|
if data == None or data == '':
|
||||||
|
raise DoneException
|
||||||
|
print data
|
||||||
|
|
||||||
|
def checkTimeout(self):
|
||||||
|
if self.timestamp + self.timeout < int(time.time()):
|
||||||
|
raise TimeoutException()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.sock.close()
|
||||||
|
|
||||||
|
|
||||||
|
sSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
sSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
sSock.bind(("", 9090))
|
||||||
|
sSock.listen(5)
|
||||||
|
print "sSock: ", sSock.fileno()
|
||||||
|
|
||||||
|
p = select.poll()
|
||||||
|
p.register(sSock.fileno(), select.POLLIN)
|
||||||
|
|
||||||
|
clients = {}
|
||||||
|
|
||||||
|
while True:
|
||||||
|
events = p.poll(1000)
|
||||||
|
|
||||||
|
for (fd, event) in events:
|
||||||
|
# print "fd: %d, event: %d" % (fd, event)
|
||||||
|
|
||||||
|
if fd == sSock.fileno() and (event & select.POLLIN):
|
||||||
|
# print "received connect"
|
||||||
|
cSock, cAddress = sSock.accept()
|
||||||
|
clients[cSock.fileno()] = Client(cSock, cAddress)
|
||||||
|
# print "cSock: %d, address: %s" % (cSock.fileno(), str(cAddress))
|
||||||
|
p.register(cSock.fileno(), select.POLLIN)
|
||||||
|
else:
|
||||||
|
# print "received data for ", fd
|
||||||
|
if event & select.POLLIN:
|
||||||
|
client = clients[fd]
|
||||||
|
try:
|
||||||
|
client.process()
|
||||||
|
except:
|
||||||
|
# print "Closing %d" % fd
|
||||||
|
client.close()
|
||||||
|
del clients[fd]
|
||||||
|
p.unregister(fd)
|
||||||
|
|
||||||
|
# print "clients: " + str(clients)
|
||||||
|
for fd in clients.keys():
|
||||||
|
try:
|
||||||
|
clients[fd].checkTimeout()
|
||||||
|
except TimeoutException:
|
||||||
|
# print "Timeout %d" % fd
|
||||||
|
clients[fd].close()
|
||||||
|
del clients[fd]
|
||||||
|
p.unregister(fd)
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user