首页 编程教程正文

Python基于select实现的socket服务器

piaodoo 编程教程 2020-02-02 12:36:40 962 0 python教程

这篇文章主要介绍了Python基于select实现的socket服务器,实例分析了Python基于select与socket模块实现socket通信的相关技巧,需要的朋友可以参考下

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

借鉴了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()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:http://www.piaodoo.com/2615.html

评论

搜索