最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python基于select實(shí)現(xiàn)的socket服務(wù)器

 更新時(shí)間:2016年04月13日 10:10:07   作者:asdfsx  
這篇文章主要介紹了Python基于select實(shí)現(xiàn)的socket服務(wù)器,實(shí)例分析了Python基于select與socket模塊實(shí)現(xiàn)socket通信的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了Python基于select實(shí)現(xiàn)的socket服務(wù)器。分享給大家供大家參考,具體如下:

借鑒了asyncore模塊中select.select的使用方法

import socket
import traceback
import select
EOL1 = 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] = 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()

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

随州市| 内黄县| 团风县| 鄂尔多斯市| 岳池县| 元朗区| 含山县| 蕲春县| 堆龙德庆县| 临泉县| 凤阳县| 长宁区| 连江县| 灵石县| 丁青县| 开江县| 德兴市| 东明县| 昔阳县| 贞丰县| 保定市| 兴隆县| 新安县| 新宾| 奉节县| 邢台县| 垦利县| 祁连县| 旺苍县| 洛扎县| 板桥市| 长葛市| 自贡市| 卓尼县| 南开区| 垣曲县| 阜新市| 安国市| 温泉县| 宁蒗| 西畴县|