国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python基于select實現的socket服務器

2020-01-04 17:32:46
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Python基于select實現的socket服務器,實例分析了Python基于select與socket模塊實現socket通信的相關技巧,需要的朋友可以參考下
 

本文實例講述了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 coming"except Exception,e:  print traceback.print_exc()  serversocket.close()
 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黑河市| 井冈山市| 霍山县| 阳山县| 新蔡县| 拉萨市| 吕梁市| 永顺县| 平武县| 玉溪市| 浠水县| 五河县| 永和县| 罗城| 彰化县| 进贤县| 军事| 手游| 凯里市| 大港区| 寻乌县| 河西区| 怀集县| 广南县| 东丰县| 江阴市| 淮阳县| 西林县| 陇南市| 岫岩| 洱源县| 三门峡市| 贡山| 福建省| 翁牛特旗| 务川| 杭锦后旗| 信阳市| 彭山县| 贡嘎县| 嵩明县|