侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python select.select模块通信全过程解析

Python  /  管理员 发布于 7年前   180

要理解select.select模块其实主要就是要理解它的参数, 以及其三个返回值。

select()方法接收并监控3个通信列表, 第一个是所有的输入的data,就是指外部发过来的数据,第2个是监控和接收所有要发出去的data(outgoing data),第3个监控错误信息

在网上一直在找这个select.select的参数解释, 但实在是没有, 哎...自己硬着头皮分析了一下。
readable, writable, exceptional = select.select(inputs, outputs, inputs)

第一个参数就是服务器端的socket, 第二个是我们在运行过程中存储的客户端的socket, 第三个存储错误信息。
重点是在返回值, 第一个返回的是可读的list, 第二个存储的是可写的list, 第三个存储的是错误信息的
list。

这个也不必深究, 看看代码自己分析下就能有大概理解。

网上所有关于select.select的代码都是差不多的, 但是有些不能运行, 或是不全。我自己重新写了一份能运行的程序, 做了很多注释, 好好看看就能搞懂

服务器端:

# coding: utf-8import selectimport socketimport Queuefrom time import sleep# Create a TCP/IPserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.setblocking(False)# Bind the socket to the portserver_address = ('localhost', 8090)print ('starting up on %s port %s' % server_address)server.bind(server_address)# Listen for incoming connectionsserver.listen(5)# Sockets from which we expect to readinputs = [server]# Sockets to which we expect to write# 处理要发送的消息outputs = []# Outgoing message queues (socket: Queue)message_queues = {}while inputs: # Wait for at least one of the sockets to be ready for processing print ('waiting for the next event') # 开始select 监听, 对input_list 中的服务器端server 进行监听 # 一旦调用socket的send, recv函数,将会再次调用此模块 readable, writable, exceptional = select.select(inputs, outputs, inputs) # Handle inputs # 循环判断是否有客户端连接进来, 当有客户端连接进来时select 将触发 for s in readable:  # 判断当前触发的是不是服务端对象, 当触发的对象是服务端对象时,说明有新客户端连接进来了  # 表示有新用户来连接  if s is server:   # A "readable" socket is ready to accept a connection   connection, client_address = s.accept()   print ('connection from', client_address)   # this is connection not server   connection.setblocking(0)   # 将客户端对象也加入到监听的列表中, 当客户端发送消息时 select 将触发   inputs.append(connection)   # Give the connection a queue for data we want to send   # 为连接的客户端单独创建一个消息队列,用来保存客户端发送的消息   message_queues[connection] = Queue.Queue()  else:   # 有老用户发消息, 处理接受   # 由于客户端连接进来时服务端接收客户端连接请求,将客户端加入到了监听列表中(input_list), 客户端发送消息将触发   # 所以判断是否是客户端对象触发   data = s.recv(1024)   # 客户端未断开   if data != '':    # A readable client socket has data    print ('received "%s" from %s' % (data, s.getpeername()))    # 将收到的消息放入到相对应的socket客户端的消息队列中    message_queues[s].put(data)    # Add output channel for response    # 将需要进行回复操作socket放到output 列表中, 让select监听    if s not in outputs:     outputs.append(s)   else:    # 客户端断开了连接, 将客户端的监听从input列表中移除    # Interpret empty result as closed connection    print ('closing', client_address)    # Stop listening for input on the connection    if s in outputs:     outputs.remove(s)    inputs.remove(s)    s.close()    # Remove message queue    # 移除对应socket客户端对象的消息队列    del message_queues[s] # Handle outputs # 如果现在没有客户端请求, 也没有客户端发送消息时, 开始对发送消息列表进行处理, 是否需要发送消息 # 存储哪个客户端发送过消息 for s in writable:  try:   # 如果消息队列中有消息,从消息队列中获取要发送的消息   message_queue = message_queues.get(s)   send_data = ''   if message_queue is not None:    send_data = message_queue.get_nowait()   else:    # 客户端连接断开了    print "has closed "  except Queue.Empty:   # 客户端连接断开了   print "%s" % (s.getpeername())   outputs.remove(s)  else:   # print "sending %s to %s " % (send_data, s.getpeername)   # print "send something"   if message_queue is not None:    s.send(send_data)   else:    print "has closed "   # del message_queues[s]   # writable.remove(s)   # print "Client %s disconnected" % (client_address) # # Handle "exceptional conditions" # 处理异常的情况 for s in exceptional:  print ('exception condition on', s.getpeername())  # Stop listening for input on the connection  inputs.remove(s)  if s in outputs:   outputs.remove(s)  s.close()  # Remove message queue  del message_queues[s] sleep(1)

客户端:

# coding: utf-8import socketmessages = ['This is the message ', 'It will be sent ', 'in parts ', ]server_address = ('localhost', 8090)# Create aTCP/IP socketsocks = [socket.socket(socket.AF_INET, socket.SOCK_STREAM), socket.socket(socket.AF_INET, socket.SOCK_STREAM), ]# Connect thesocket to the port where the server is listeningprint ('connecting to %s port %s' % server_address)# 连接到服务器for s in socks: s.connect(server_address)for index, message in enumerate(messages): # Send messages on both sockets for s in socks:  print ('%s: sending "%s"' % (s.getsockname(), message + str(index)))  s.send(bytes(message + str(index)).decode('utf-8')) # Read responses on both socketsfor s in socks: data = s.recv(1024) print ('%s: received "%s"' % (s.getsockname(), data)) if data != "":  print ('closingsocket', s.getsockname())  s.close()

写代码过程中遇到了两个问题, 一是如何判断客户端已经关闭了socket连接, 后来自己分析了下, 如果关闭了客户端socket, 那么此时服务器端接收到的data就是'', 加个这个判断。二是如果服务器端关闭了socket, 一旦在调用socket的相关方法都会报错, 不管socket是不是用不同的容器存储的(意思是说list_1存储了socket1, list_2存储了socket1, 我关闭了socket1, 两者都不能在调用这个socket了)

客户端:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python+Selenium+PIL+Tesseract自动识别验证码进行一键登录
    下一条:
    基于python的字节编译详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客