Python基于select实现的socket服务器 Python基于select实现的socket服务器

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python基于select实现的socket服务器 Python基于select实现的socket服务器

asdfsx   2021-03-22 我要评论
想了解Python基于select实现的socket服务器的相关内容吗,asdfsx在本文为您仔细讲解Python基于select实现的socket服务器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,select,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程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们