
基于python select.select模塊通信的實(shí)例講解
要理解select.select模塊其實(shí)主要就是要理解它的參數(shù), 以及其三個(gè)返回值。
select()方法接收并監(jiān)控3個(gè)通信列表, 第一個(gè)是所有的輸入的data,就是指外部發(fā)過(guò)來(lái)的數(shù)據(jù),第2個(gè)是監(jiān)控和接收所有要發(fā)出去的data(outgoing data),第3個(gè)監(jiān)控錯(cuò)誤信息在網(wǎng)上一直在找這個(gè)select.select的參數(shù)解釋, 但實(shí)在是沒(méi)有, 哎...自己硬著頭皮分析了一下。
readable, writable, exceptional = select.select(inputs, outputs, inputs)
第一個(gè)參數(shù)就是服務(wù)器端的socket, 第二個(gè)是我們?cè)谶\(yùn)行過(guò)程中存儲(chǔ)的客戶端的socket, 第三個(gè)存儲(chǔ)錯(cuò)誤信息。
重點(diǎn)是在返回值, 第一個(gè)返回的是可讀的list, 第二個(gè)存儲(chǔ)的是可寫(xiě)的list, 第三個(gè)存儲(chǔ)的是錯(cuò)誤信息的list。
這個(gè)也不必深究, 看看代碼自己分析下就能有大概理解。
網(wǎng)上所有關(guān)于select.select的代碼都是差不多的, 但是有些不能運(yùn)行, 或是不全。我自己重新寫(xiě)了一份能運(yùn)行的程序, 做了很多注釋, 好好看看就能搞懂
服務(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')
# 開(kāi)始select 監(jiān)聽(tīng), 對(duì)input_list 中的服務(wù)器端server 進(jìn)行監(jiān)聽(tīng)
# 一旦調(diào)用socket的send, recv函數(shù),將會(huì)再次調(diào)用此模塊
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
# 循環(huán)判斷是否有客戶端連接進(jìn)來(lái), 當(dāng)有客戶端連接進(jìn)來(lái)時(shí)select 將觸發(fā)
for s in readable:
# 判斷當(dāng)前觸發(fā)的是不是服務(wù)端對(duì)象, 當(dāng)觸發(fā)的對(duì)象是服務(wù)端對(duì)象時(shí),說(shuō)明有新客戶端連接進(jìn)來(lái)了
# 表示有新用戶來(lái)連接
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)
# 將客戶端對(duì)象也加入到監(jiān)聽(tīng)的列表中, 當(dāng)客戶端發(fā)送消息時(shí) select 將觸發(fā)
inputs.append(connection)
# Give the connection a queue for data we want to send
# 為連接的客戶端單獨(dú)創(chuàng)建一個(gè)消息隊(duì)列,用來(lái)保存客戶端發(fā)送的消息
message_queues[connection] = Queue.Queue()
else:
# 有老用戶發(fā)消息, 處理接受
# 由于客戶端連接進(jìn)來(lái)時(shí)服務(wù)端接收客戶端連接請(qǐng)求,將客戶端加入到了監(jiān)聽(tīng)列表中(input_list), 客戶端發(fā)送消息將觸發(fā)
# 所以判斷是否是客戶端對(duì)象觸發(fā)
data = s.recv(1024)
# 客戶端未斷開(kāi)
if data != '':
# A readable client socket has data
print ('received "%s" from %s' % (data, s.getpeername()))
# 將收到的消息放入到相對(duì)應(yīng)的socket客戶端的消息隊(duì)列中
message_queues[s].put(data)
# Add output channel for response
# 將需要進(jìn)行回復(fù)操作socket放到output 列表中, 讓select監(jiān)聽(tīng)
if s not in outputs:
outputs.append(s)
else:
# 客戶端斷開(kāi)了連接, 將客戶端的監(jiān)聽(tīng)從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
# 移除對(duì)應(yīng)socket客戶端對(duì)象的消息隊(duì)列
del message_queues[s]
# Handle outputs
# 如果現(xiàn)在沒(méi)有客戶端請(qǐng)求, 也沒(méi)有客戶端發(fā)送消息時(shí), 開(kāi)始對(duì)發(fā)送消息列表進(jìn)行處理, 是否需要發(fā)送消息
# 存儲(chǔ)哪個(gè)客戶端發(fā)送過(guò)消息
for s in writable:
try:
# 如果消息隊(duì)列中有消息,從消息隊(duì)列中獲取要發(fā)送的消息
message_queue = message_queues.get(s)
send_data = ''
if message_queue is not None:
send_data = message_queue.get_nowait()
else:
# 客戶端連接斷開(kāi)了
print "has closed "
except Queue.Empty:
# 客戶端連接斷開(kāi)了
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()
寫(xiě)代碼過(guò)程中遇到了兩個(gè)問(wèn)題, 一是如何判斷客戶端已經(jīng)關(guān)閉了socket連接, 后來(lái)自己分析了下, 如果關(guān)閉了客戶端socket, 那么此時(shí)服務(wù)器端接收到的data就是'', 加個(gè)這個(gè)判斷。二是如果服務(wù)器端關(guān)閉了socket, 一旦在調(diào)用socket的相關(guān)方法都會(huì)報(bào)錯(cuò), 不管socket是不是用不同的容器存儲(chǔ)的(意思是說(shuō)list_1存儲(chǔ)了socket1, list_2存儲(chǔ)了socket1, 我關(guān)閉了socket1, 兩者都不能在調(diào)用這個(gè)socket了)
服務(wù)器端:
客戶端:
以上這篇基于python select.select模塊通信的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書(shū)考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開(kāi)啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03