zoukankan      html  css  js  c++  java
  • select实现socket多并发

    __author__ = "Leo"
    import select
    import socket
    import queue

    server=socket.socket()
    server.bind(('localhost',8568))
    server.listen(1000)

    server.setblocking(0)
    inputs=[server, ]
    #inputs=[server, conn1,conn2]#连接对象(来自client)
    outputs=[] #返回数据
    #outputs=[r1,r2]#要返回给客户端的连接列表
    msg_dict={}
    while True:
    readale, writebale, excptional = select.select(inputs, outputs, inputs) # 如果没有任何fd就绪,程序就会一直阻塞在这里
    print(readale, writebale, excptional)
    for r in readale:#每个r就是一个socket
    if r is server:#代表来了一个新连接
    conn,add=server.accept()
    print(conn,add)
    inputs.append(conn)#新建立的连接还未发送数据,现在接受程序就报错
    #所以要想实现这个客户端要想实现这个客户端发送数据来时server端能知道,
    #就需要这个selece在监测 gvbd
    msg_dict[conn]=queue.Queue()#初始化一个队列,后面存要返回给客户端的数据。接收到客户端的数据后,不立刻返回而是暂存在队列中,以后再发送。
    else:#如果不是新连接,那就收数据
    data=r.recv(1024)
    if data:#如果收到的数据不为空
    print("recv data:",data.decode())
    msg_dict[r].put(data)#收到的数据先放到queue里,一会再返回数据给客户端
    if r not in outputs:
    outputs.append(r)#放入返回的连接队列里
    else: #如果收不到data,代表客户端断开连接了
    print("客户端断开了", s)

    if r in outputs:
    outputs.remove(s) # 清理已断开的连接

    inputs.remove(s) # 清理已断开的连接

    del msg_dict[r] ##清理已断开的连接

    # r.send(data.upper())
    # print("send done...")
    for w in writebale:#要返回给客户端的数据
    data_to_client=msg_dict[w].get()#获取队列中的数据
    w.send(data_to_client)#返回客户端数据源
    outputs.remove(w)#确保下次循环的时候不返回已经处理的连接

    for e in excptional:
    if e in outputs:
    outputs.remove(e)
    inputs.remove(e)
  • 相关阅读:
    兼容ie6的mvvm框架--san
    Parsing error: The keyword 'export' is reserved && error Parsing error: Unexpected token <
    Call to undefined function openssl_decrypt()
    css 陌生属性
    获取url
    relative 和 absolute
    SSL certificate problem: unable to get local issuer certificate 的解决方法
    使用wamp扩展php时出现服务未启动的解决方法
    php判断是不是移动设备
    js:不是空字符串的空字符串引起的bug
  • 原文地址:https://www.cnblogs.com/WhatTTEver/p/6834269.html
Copyright © 2011-2022 走看看