本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下:
借鉴了asyncore模块中select.select的使用方法
import socketimport tracebackimport selectEol1 = 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] = serversocketprint 'Listening_fileno',Listening_filenotry: while True: r,[] for fd in socketmap: r.append(fd) w.append(fd) e.append(fd) r,e = select.select(r,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相关内容感兴趣的读者可查看本站专题:《Python字符串 *** 作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录 *** 作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
总结以上是内存溢出为你收集整理的Python基于select实现的socket服务器全部内容,希望文章能够帮你解决Python基于select实现的socket服务器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)