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 119 120 121 122 123 124 125 126 127 128 129 130 131 132
| import socket, logging import select, errno
logger = logging.getLogger("network-server")
def InitLog(): logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("network-server.log") fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.ERROR)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) fh.setFormatter(formatter)
logger.addHandler(fh) logger.addHandler(ch)
if __name__ == "__main__":
InitLog()
try: listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) except socket.error as msg: logger.error("create socket failed")
try: listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error as msg: logger.error("setsocketopt SO_REUSEADDR failed")
try: listen_fd.bind(('127.0.0.1', 8008)) except socket.error as msg: logger.error("bind failed")
try: listen_fd.listen(100) except socket.error as msg: logger.error(msg)
try: epoll_fd = select.epoll() epoll_fd.register(listen_fd.fileno(), select.EPOLLIN) except select.error as msg: logger.error(msg)
connections = {} addresses = {} datalist = {} while True: epoll_list = epoll_fd.poll()
for fd, events in epoll_list: if fd == listen_fd.fileno(): conn, addr = listen_fd.accept() logger.debug("accept connection from %s, %d, fd = %d" % (addr[0], addr[1], conn.fileno())) conn.setblocking(0) epoll_fd.register(conn.fileno(), select.EPOLLIN | select.EPOLLET) connections[conn.fileno()] = conn addresses[conn.fileno()] = addr elif select.EPOLLIN & events: datas = '' while True: try: data = connections[fd].recv(10) if not data and not datas: epoll_fd.unregister(fd) connections[fd].close() logger.debug("%s, %d closed" % (addresses[fd][0], addresses[fd][1])) break else: datas += data except socket.error as msg: if msg.errno == errno.EAGAIN: logger.debug("%s receive %s" % (fd, datas)) datalist[fd] = datas epoll_fd.modify(fd, select.EPOLLET | select.EPOLLOUT) break else: epoll_fd.unregister(fd) connections[fd].close() logger.error(msg) break elif select.EPOLLHUP & events: epoll_fd.unregister(fd) connections[fd].close() logger.debug("%s, %d closed" % (addresses[fd][0], addresses[fd][1])) elif select.EPOLLOUT & events: sendLen = 0 while True: sendLen += connections[fd].send(datalist[fd][sendLen:]) if sendLen == len(datalist[fd]): break epoll_fd.modify(fd, select.EPOLLIN | select.EPOLLET) else: continue
|