python io多路复用

            

用for循环执行多用户访问

SEVER

 

import socket
sk1 = socket.socket()
sk1.bind(('127.0.0.1', 888))
sk1.listen()
import select
ipt = [sk1, ]
output = []
message_dic={}
eer=[]
while True:
    r_list, w_list, e_list = select.select(ipt, output, eer, 1)
    print('正在监听的sk对象 %s' % len(ipt))
    print(r_list)
    # for con in w_list:
        # con.sendall(bytes('hey', encoding='utf-8'))
        # output.remove(con)
    for sk_con in r_list:
        if sk_con == sk1:
            # 表示新客户来
            con, addr = sk_con.accept()
            ipt.append(con)
            message_dic[con]=[]
        else:
            # 老客户发消息
            try:
                data_bytes = sk_con.recv(1024)
                # data_str = str(data_bytes, encoding='utf-8')
                # sk.sendall(bytes(data_str + 'hao', encoding='utf-8'))
            except ConnectionResetError:
                eer.append(sk_con)
            else:
                # 用户正常发消息
                data_str = str(data_bytes, encoding='utf-8')
                message_dic[sk_con].append(data_str)
                output.append(sk_con)
                # ipt.remove(sk)
                # con.sendall(bytes('hi',encoding='utf-8'))
                # for sk in e_list:
                #     ipt.remove(sk)
    for cont in w_list:
        rec_str=message_dic[cont][0]
        cont.sendall(bytes(rec_str+'hhhhh',encoding='utf-8'))
        del message_dic[cont][0]
        output.remove(cont)
    for sk in e_list:
        ipt.remove(sk)

 

sk1=socket.socket()
sk1.bind(('127.0.0.1',888))
sk1.listen()

import select
ipt=[sk1,]
output=[]
while True:
    r_list, w_list, e_list = select.select(ipt, output, ipt, 1)
    print('正在监听的sk对象 %s' % len(ipt))
    print(r_list)
    for con in w_list:
        con.sendall(bytes('hey', encoding='utf-8'))
        output.remove(con)
    for sk in r_list:
        if sk==sk1:
            # 表示新客户来了
            con,addr=sk.accept()
            ipt.append(con)
        else:
            # 老客户发消息
            try:
                data_bytes=sk.recv(1024)
                data_str=str(data_bytes,encoding='utf-8')
                sk.sendall(bytes(data_str+'hao',encoding='utf-8'))
            except ConnectionResetError:
                output.append(sk)
                # ipt.remove(sk)
        # con.sendall(bytes('hi',encoding='utf-8'))

    # for sk in e_list:
    #     ipt.remove(sk)

 

 

转载于:https://www.cnblogs.com/ezway/p/6725589.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值