玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python select简单实现socket服务器的方法

python 培训

玩蛇网本文为大家提供了关于Python select简单实现socket服务器的方法源码示例。源码编写借鉴了asyncore模块中select.select的使用方法,并使用了Python的socket、traceback和select模块方法。

什么是socket服务器?Socket服务器主要用于提供高效及稳定的数据信息处理,和消息的转发等服务。socket服务器直接决定了前台应用程序的性能。

Python select简单实现socket服务器的方法源码如下:

#导入方法模块
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)
#www.iplaypython.com

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源码首要一定要加上编码声明,这是一个好的编程习惯。

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/other/o2695.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-01-05 09:56 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部