
基于python select.select模塊通信的實例講解
要理解select.select模塊其實主要就是要理解它的參數(shù), 以及其三個返回值。
select()方法接收并監(jiān)控3個通信列表, 第一個是所有的輸入的data,就是指外部發(fā)過來的數(shù)據(jù),第2個是監(jiān)控和接收所有要發(fā)出去的data(outgoing data),第3個監(jiān)控錯誤信息在網(wǎng)上一直在找這個select.select的參數(shù)解釋, 但實在是沒有, 哎...自己硬著頭皮分析了一下。
readable, writable, exceptional = select.select(inputs, outputs, inputs)
第一個參數(shù)就是服務(wù)器端的socket, 第二個是我們在運行過程中存儲的客戶端的socket, 第三個存儲錯誤信息。
重點是在返回值, 第一個返回的是可讀的list, 第二個存儲的是可寫的list, 第三個存儲的是錯誤信息的list。
這個也不必深究, 看看代碼自己分析下就能有大概理解。
網(wǎng)上所有關(guān)于select.select的代碼都是差不多的, 但是有些不能運行, 或是不全。我自己重新寫了一份能運行的程序, 做了很多注釋, 好好看看就能搞懂
服務(wù)器端:
# coding: utf-8
import select
import socket
import Queue
from time import sleep
# Create a TCP/IP
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(False)
# Bind the socket to the port
server_address = ('localhost', 8090)
print ('starting up on %s port %s' % server_address)
server.bind(server_address)
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
inputs = [server]
# Sockets to which we expect to write
# 處理要發(fā)送的消息
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 監(jiān)聽, 對input_list 中的服務(wù)器端server 進行監(jiān)聽
# 一旦調(diào)用socket的send, recv函數(shù),將會再次調(diào)用此模塊
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
# 循環(huán)判斷是否有客戶端連接進來, 當(dāng)有客戶端連接進來時select 將觸發(fā)
for s in readable:
# 判斷當(dāng)前觸發(fā)的是不是服務(wù)端對象, 當(dāng)觸發(fā)的對象是服務(wù)端對象時,說明有新客戶端連接進來了
# 表示有新用戶來連接
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)
# 將客戶端對象也加入到監(jiān)聽的列表中, 當(dāng)客戶端發(fā)送消息時 select 將觸發(fā)
inputs.append(connection)
# Give the connection a queue for data we want to send
# 為連接的客戶端單獨創(chuàng)建一個消息隊列,用來保存客戶端發(fā)送的消息
message_queues[connection] = Queue.Queue()
else:
# 有老用戶發(fā)消息, 處理接受
# 由于客戶端連接進來時服務(wù)端接收客戶端連接請求,將客戶端加入到了監(jiān)聽列表中(input_list), 客戶端發(fā)送消息將觸發(fā)
# 所以判斷是否是客戶端對象觸發(fā)
data = s.recv(1024)
# 客戶端未斷開
if data != '':
# A readable client socket has data
print ('received "%s" from %s' % (data, s.getpeername()))
# 將收到的消息放入到相對應(yīng)的socket客戶端的消息隊列中
message_queues[s].put(data)
# Add output channel for response
# 將需要進行回復(fù)操作socket放到output 列表中, 讓select監(jiān)聽
if s not in outputs:
outputs.append(s)
else:
# 客戶端斷開了連接, 將客戶端的監(jiān)聽從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
# 移除對應(yīng)socket客戶端對象的消息隊列
del message_queues[s]
# Handle outputs
# 如果現(xiàn)在沒有客戶端請求, 也沒有客戶端發(fā)送消息時, 開始對發(fā)送消息列表進行處理, 是否需要發(fā)送消息
# 存儲哪個客戶端發(fā)送過消息
for s in writable:
try:
# 如果消息隊列中有消息,從消息隊列中獲取要發(fā)送的消息
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-8
import socket
messages = ['This is the message ', 'It will be sent ', 'in parts ', ]
server_address = ('localhost', 8090)
# Create aTCP/IP socket
socks = [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 listening
print ('connecting to %s port %s' % server_address)
# 連接到服務(wù)器
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 sockets
for s in socks:
data = s.recv(1024)
print ('%s: received "%s"' % (s.getsockname(), data))
if data != "":
print ('closingsocket', s.getsockname())
s.close()
寫代碼過程中遇到了兩個問題, 一是如何判斷客戶端已經(jīng)關(guān)閉了socket連接, 后來自己分析了下, 如果關(guān)閉了客戶端socket, 那么此時服務(wù)器端接收到的data就是'', 加個這個判斷。二是如果服務(wù)器端關(guān)閉了socket, 一旦在調(diào)用socket的相關(guān)方法都會報錯, 不管socket是不是用不同的容器存儲的(意思是說list_1存儲了socket1, list_2存儲了socket1, 我關(guān)閉了socket1, 兩者都不能在調(diào)用這個socket了)
服務(wù)器端:
客戶端:
以上這篇基于python select.select模塊通信的實例講解就是小編分享給大家的全部內(nèi)容了
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10