Python基于select实现的socket服务器

yipeiwu_com6年前服务器

本文实例讲述了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探索之实现一个简单的HTTP服务器

Python标准库中的BaseHTTPServer模块实现了一个基础的HTTP服务器基类和HTTP请求处理类。这在文章python探索之BaseHTTPServer-实现Web服务器介绍...

使用 Python 快速实现 HTTP 和 FTP 服务器的方法

有时你需临时搭建一个简单的 Web Server,但你又不想去安装 Apache、Nginx 等这类功能较复杂的 HTTP 服务程序时。这时可以使用 Python 内建的 SimpleH...

Windows服务器中PHP如何安装redis扩展

Windows服务器中PHP如何安装redis扩展

一、总结 一句话总结:下载扩展的dll,放入指定文件夹(php对应的扩展的目录php/ext),在配置文件php.ini中注册dll 尽量不要选择最新版php和redis扩展,下载时文件...

php服务器的系统详解

PHP服务器使用什么操作系统 windows系统和Linux系统都可以的,他们各有各的好处。 1、windows服务器 windows服务器操作方便适用于php初学者,随着Windows...

python3实现微型的web服务器

实验目的:用socket 模拟一个微型的web服务器,当py脚本run起后,实微型web server架起了,然后用本地浏览器访问127.0.0.1:8080(web serv...