zoukankan      html  css  js  c++  java
  • Server 非阻塞

    import socket
    import select
    import Queue
    
    port =500
    host = ""
    
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.setblocking(False)
    
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind((host,port))
    sock.listen(10)
    print "server is running on port %d; press Ctrl-c to terminate." % port
    rlists =[sock]
    wlists=[]
    
    msg_que={}
    timeout =20
    
    while rlists:
    #读,写,错误
    rs,ws,es = select.select(rlists,wlists,rlists,timeout)
    #3个对象集合
    
    if not(rs or ws or es):
    print 'timeout...'
    continue
    break
    for s in rs:
    if s is sock:
    conn,addr = s.accept()
    print 'connect by',addr
    conn.setblocking(False)
    rlists.append(conn)
    msg_que[conn] = Queue.Queue()
    else:
    data = s.recv(1024)
    if data:
    print data
    msg_que[s].put(data)
    if s not in wlists:
    wlists.append(s)
    else:
    if s in wlists:
    wlists.remove(s)
    rlists.remove(s)
    s.close()
    del msg_que[s]
    for s in ws:
    try:
    msg = msg_que[s].get_nowait()
    except Queue.Empty:
    print 'msg empty'
    wlists.remove(s)
    else:
    s.send(msg)
    
    for s in es:
    print 'except',s.getpeername()
    if s in rlists:
    rlists.remove(s)
    if s in wlists:
    wlists.remove(s)
    rlists.remove(s)
    wlists.remove(s)
    s.close()
    del msg_que[s]
  • 相关阅读:
    浅析数据库安全技术
    本站快捷付款方式
    VMware Workstation 官方正式版及激活密钥
    Win10真正好用之处
    我眼中的CentOS 下 安全策略
    美团
    Tomcat connector元素常用配置(最大连接数等)
    9.22面经:
    9.7
    合并两个有序数组为一个新的有序数组
  • 原文地址:https://www.cnblogs.com/123ing/p/3978883.html
Copyright © 2011-2022 走看看