Python基于select实现的socket服务器
本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下:
借鉴了asyncore模块中select.select的使用方法
importsocket importtraceback importselect EOL1=b'\n\n' EOL2=b'\n\r\n' socketmap={} r,w,e=[],[],[] response=b'HTTP/1.0200OK\r\nDate:Mon,1Jan199601:01:01GMT\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: whileTrue: r,w,e=[],[],[] forfdinsocketmap: r.append(fd) w.append(fd) e.append(fd) r,w,e=select.select(r,w,e,1) forfdinr: request=b'' isocket=socketmap[fd] iffd==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' whileEOL1notinrequestandEOL2notinrequest: request+=isocket.recv(1024) print(request.decode()) forfdinw: print'writing' osocket=socketmap[fd] osocket.send(response) forfdine: esocket=socketmap[fd] print'socketclose',fd esocket.close() delsocketmap[fd] print"nodatacoming" exceptException,e: printtraceback.print_exc() serversocket.close()
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。