socket + select 完成伪并发操作的实例

作者:袖梨 2022-06-25
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import socket
#创建一个socket对象
sk1 = socket.socket()
#绑定ip和端口
sk1.bind(('127.0.0.1', 8001))
#监听
sk1.listen()
#定义一个字典存放客户端发送的信息
message_dict = {}
#inputs用于存放socket对象
inputs = [sk1]
#哪一个客户端发送信息就把哪一个客户端的存放进output
output = []
import select
while True:
  r_list, w_list, e_list = select.select(inputs, output, inputs, 1)
  print('正在监听的socket%d' %len(inputs))
  print(r_list)
  for sk_or_conn in r_list:
    if sk_or_conn == sk1:
      conn, address = sk_or_conn.accept()
      inputs.append(conn)
      message_dict[conn] = []
    else:
      try:
        data_bytes = sk_or_conn.recv(1024)
      except Exception as ex:
        inputs.remove(sk_or_conn)
      else:
        data_str = str(data_bytes, encoding='utf-8')
        message_dict[sk_or_conn].append(data_str)
        output.append(sk_or_conn)
  for conn in w_list:
    data_message = message_dict[sk_or_conn][0]
    del message_dict[sk_or_conn][0]
    conn.sendall(bytes(data_message + '好',encoding='utf-8'))
    output.remove(conn)

相关文章

精彩推荐