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程序设计有所帮助。

相关文章

Python 实现两个服务器之间文件的上传方法

如下所示: # coding: utf-8 import paramiko import MySQLdb def main(): connection=MySQLdb.connec...

Python实现的服务器示例小结【单进程、多进程、多线程、非阻塞式】

本文实例讲述了Python实现的服务器。分享给大家供大家参考,具体如下: python - 单进程服务器 #coding=utf-8 from socket import * #创建...

PHP多个文件上传到服务器实例

本文实例讲述了PHP多个文件上传到服务器的实现方法。对于多个文件同时上传到服务器的情况来说,我们需要使用到数组形式的参数传递及数据的遍历上传即可,具体的操作步骤分析如下: 一、实例说明...

python远程连接服务器MySQL数据库

本文实例为大家分享了python远程连接服务器MySQL数据库的具体代码,供大家参考,具体内容如下 这里默认大家都已经配置安装好 MySQL 和 Python 的MySQL 模块,且默认...

python实现数据库跨服务器迁移

 基于Python2.7的版本环境,Python实现的数据库跨服务器(跨库)迁移, 每以5000条一查询一提交,代码中可以自行更改每次查询提交数目. # -*- codin...