Python基于select实现的socket服务器

yipeiwu_com5年前服务器

本文实例讲述了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程序设计有所帮助。

相关文章

Pycharm使用远程linux服务器conda/python环境在本地运行的方法(图解))

Pycharm使用远程linux服务器conda/python环境在本地运行的方法(图解))

1.首先在Pycharm Tools->Deployment->Configurations打开 新建SFTP输入host: ip地址username密码然后点击Test C...

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

环境搭建 软件: xampp   下载地址:https://www.apachefriends.org/zh_cn/index.html (建议使用迅雷下载,不然速度...

python高并发异步服务器核心库forkcore使用方法

1 拷贝下面的代码到一个文件,并命名为forkcore.py 复制代码 代码如下:import osimport threadingimport selectimport socket...

Python Web程序部署到Ubuntu服务器上的方法

Python Web程序部署到Ubuntu服务器上的方法

在本文记录了我在Ubuntu中部署Flask Web站点的过程, 其中包括用户创建、代码获取、Python3环境的安装、虚拟环境设置、uWSGI启动程序设置,并将Nginx作为前端反向代...

python定时采集摄像头图像上传ftp服务器功能实现

首先是截图,从摄像头截取一幅图像: 复制代码 代码如下:while 1:   #测试摄像头的存在    try:  ...