您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python基于select实现的socket服务器

2024/2/27 22:46:38发布14次查看
本文实例讲述了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,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 comingexcept exception,e: print traceback.print_exc() serversocket.close()
更多关于python相关内容感兴趣的读者可查看本站专题:《python字符串操作技巧汇总》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总》
希望本文所述对大家python程序设计有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product