手机
当前位置:查字典教程网 >脚本专栏 >python >Python基于select实现的socket服务器
Python基于select实现的socket服务器
摘要:本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下:借鉴了asyncore模块中select...

本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下:

借鉴了asyncore模块中select.select的使用方法

import socket import traceback import select EOL1 = b'nn' EOL2 = b'nrn' socketmap = {} r,w,e = [],[],[] response = b'HTTP/1.0 200 OKrnDate: Mon, 1 Jan 1996 01:01:01 GMTrn' response += b'Content-Type: text/plainrnContent-Length: 13rnrn' 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程序设计有所帮助。

【Python基于select实现的socket服务器】相关文章:

Python实现的几个常用排序算法实例

Python open读写文件实现脚本

Python3实现的腾讯微博自动发帖小工具

python和pyqt实现360的CLable控件

python实现linux服务器批量修改密码并生成execl

400多行Python代码实现了一个FTP服务器

Python实现的金山快盘的签到程序

Python 可爱的大小写

python实现哈希表

Python中使用 Selenium 实现网页截图实例

精品推荐
分类导航