Python基于select实现的socket服务器
发布时间:2020-12-16 20:49:40  所属栏目:Python  来源:网络整理 
            导读:本篇章节讲解Python基于select实现的socket服务器。供大家参考研究具体如下: 借鉴了asyncore模块中select.select的使用方法 import socketimport tracebackimport selectEOL1 = b'nn'EOL2 = b'nrn'socketmap = {}r,w,e = [],[],[]response =
                
                
                
            | 
                         本篇章节讲解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,[]
    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 – 根据两列的值选择pandas帧行
 - 使用pyvmomi在vmware中获取实例的实际使用(分配)磁盘空间
 - python – 是否有可能在scipy.spatial的Delaunay中强制执行
 - python网络编程学习笔记(七):HTML和XHTML解析(HTMLParser、
 - Python爬取qq music中的音乐url及批量下载
 - Django DB Design – 维护常用和历史数据
 - Python遍历某目录下的所有文件夹与文件路径
 - python – 在hybrid_property中Flask-SQLAlchemy多对多有序
 - Python-列表
 - Python BeautifulSoup中文乱码问题的2种解决方法
 
