详解Python基于select实现的socket服务器的示例
程序员文章站
2022-04-08 22:50:20
...
本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下:
借鉴了asyncore模块中select.select的使用方法
import socket import traceback import select EOL1 = b'\n\n' EOL2 = b'\n\r\n' socketmap = {} r,w,e = [],[],[] response = b'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n' response += b'Content-Type: text/plain\r\nContent-Length: 13\r\n\r\n' response += b'Hello, world!' serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(('0.0.0.0', 23456)) serversocket.listen(1) #serversocket.setblocking(0) listening_fileno = serversocket.fileno() socketmap[listening_fileno] = serversocket print 'listening_fileno',listening_fileno try: while True: r,w,e = [],[],[] for fd in socketmap: r.append(fd) w.append(fd) e.append(fd) r,w,e = select.select(r,w,e,1) for fd in r: request = b'' isocket = socketmap[fd] if fd == listening_fileno: print 'accepting' clientsock,clientaddr = isocket.accept() #clientsock.setblocking(0) cli_fileno = clientsock.fileno() r.append(cli_fileno) w.append(cli_fileno) e.append(cli_fileno) socketmap[cli_fileno] = clientsock else: print 'reading' while EOL1 not in request and EOL2 not in request: request += isocket.recv(1024) print(request.decode()) for fd in w: print 'writing' osocket = socketmap[fd] osocket.send(response) for fd in e: esocket = socketmap[fd] print 'socket close',fd esocket.close() del socketmap[fd] print "no data coming" except Exception,e: print traceback.print_exc() serversocket.close()
更多详解Python基于select实现的socket服务器的示例相关文章请关注PHP中文网!
下一篇: php验证码生成器实例代码
推荐阅读
-
Python简单实现的代理服务器端口映射功能示例
-
Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
-
Java编程实现基于TCP协议的Socket聊天室示例
-
Python实现的基于优先等级分配糖果问题算法示例
-
Python实现的服务器示例小结【单进程、多进程、多线程、非阻塞式】
-
Python socket实现的简单通信功能示例
-
Python基于plotly模块实现的画图操作示例
-
详解duck typing鸭子类型程序设计与Python的实现示例
-
Python3.6基于正则实现的计算器示例【无优化简单注释版】
-
Python基于property实现类的特性操作示例