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()



本文章来至源码世界  http://www.ymsky.net/views/65548.shtml 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值