Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from copy import deepcopy, copy
- from pdb import set_trace as st
- from os import fork, pipe, read, write, close, fdopen
- from sys import exit
- from socket import *
- from select import poll, POLLIN, POLLPRI, POLLHUP, POLLERR, POLLOUT
- import Queue
- from time import sleep
- import sys
- reload(sys)
- sys.setdefaultencoding('utf8')
- HOST = None
- PORT = 4500
- # Keep up with the queues of outgoing messages
- message_queues = {}
- # poll flags
- READ_ONLY = POLLIN | POLLPRI | POLLHUP | POLLERR
- READ_WRITE = READ_ONLY | POLLOUT
- for res in getaddrinfo(HOST, PORT, AF_INET, SOCK_STREAM):
- af, socktype, proto, canonname, sa = res
- # create server socket and binding it to address
- server = socket(af, socktype, proto)
- server.bind(sa)
- server.listen(5)
- server.setblocking(0)
- # Map file descriptors to socket objects
- fd_to_socket = { server.fileno(): server,
- }
- poller = poll()
- poller.register(server, READ_ONLY)
- while 1:
- events = poller.poll(100)
- for fd, flag in events:
- s = fd_to_socket[fd]
- # some checks
- if flag & (POLLIN | POLLPRI):
- if s is server: # new connection
- connection, client_addr = s.accept()
- print "Connected ", client_addr
- connection.setblocking(0)
- fd_to_socket[ connection.fileno() ] = connection
- poller.register(connection, READ_ONLY)
- message_queues[connection] = Queue.Queue()
- else: # reading new data
- data = s.recv(1024)
- if data:
- print "From %s received:\n'%s'\n" % (s, data)
- poller.modify(s, READ_WRITE)
- else: # empty string, client disconnecting
- print "Closing connection %s after reading no data"
- poller.unregister(s)
- s.close()
- del message_queues[s]
- elif flag & POLLHUP: # client dirty hangup connection
- print "Clossing connection from %s after HANGUP" % s.getpeername()
- poller.unregister(s)
- s.close()
- # del message_queues
- del message_queues[s]
- elif flag & POLLOUT: # ready send data to client
- try:
- # st()
- next_msg = message_queues[s].get_nowait()
- except Queue.Empty:
- # no writable data, so stop monitoring this connection for write
- poller.modify(s, READ_ONLY)
- print "Nothing to send to %s" % str(s.getpeername())
- else:
- print "Send %s to %s" % (next_msg, s.getpeername())
- s.send(next_msg)
- elif flag & POLLERR: # closing connection on some error
- print "Clossing connection from %s after Exception" % s.getpeername()
- poller.unregister(s)
- s.close()
- del message_queues[s]
- # conn, addr = server.accept()
- # print "Connected ", addr
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement