基于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ù)就是服務器端的socket, 第二個是我們在運行過程中存儲的客戶端的socket, 第三個存儲錯誤信息。
重點是在返回值, 第一個返回的是可讀的list, 第二個存儲的是可寫的list, 第三個存儲的是錯誤信息的list。
這個也不必深究, 看看代碼自己分析下就能有大概理解。
網(wǎng)上所有關于select.select的代碼都是差不多的, 但是有些不能運行, 或是不全。我自己重新寫了一份能運行的程序, 做了很多注釋, 好好看看就能搞懂
服務器端:
# 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 中的服務器端server 進行監(jiān)聽
# 一旦調(diào)用socket的send, recv函數(shù),將會再次調(diào)用此模塊
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
# 循環(huán)判斷是否有客戶端連接進來, 當有客戶端連接進來時select 將觸發(fā)
for s in readable:
# 判斷當前觸發(fā)的是不是服務端對象, 當觸發(fā)的對象是服務端對象時,說明有新客戶端連接進來了
# 表示有新用戶來連接
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)聽的列表中, 當客戶端發(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ā)消息, 處理接受
# 由于客戶端連接進來時服務端接收客戶端連接請求,將客戶端加入到了監(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()))
# 將收到的消息放入到相對應的socket客戶端的消息隊列中
message_queues[s].put(data)
# Add output channel for response
# 將需要進行回復操作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
# 移除對應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)
# 連接到服務器
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)關閉了socket連接, 后來自己分析了下, 如果關閉了客戶端socket, 那么此時服務器端接收到的data就是'', 加個這個判斷。二是如果服務器端關閉了socket, 一旦在調(diào)用socket的相關方法都會報錯, 不管socket是不是用不同的容器存儲的(意思是說list_1存儲了socket1, list_2存儲了socket1, 我關閉了socket1, 兩者都不能在調(diào)用這個socket了)
服務器端:

客戶端:

以上這篇基于python select.select模塊通信的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Python中使用select模塊實現(xiàn)非阻塞的IO
- 深入理解python中的select模塊
- Python通過select實現(xiàn)異步IO的方法
- Python基于select實現(xiàn)的socket服務器
- python select.select模塊通信全過程解析
- Python的Asyncore異步Socket模塊及實現(xiàn)端口轉(zhuǎn)發(fā)的例子
- 在Python中使用異步Socket編程性能測試
- Python 網(wǎng)絡編程起步(Socket發(fā)送消息)
- python socket網(wǎng)絡編程步驟詳解(socket套接字使用)
- Python網(wǎng)絡編程之TCP套接字簡單用法示例
- Python網(wǎng)絡編程使用select實現(xiàn)socket全雙工異步通信功能示例
相關文章
Python入門教程(二十)Python的Lambda表達式
這篇文章主要介紹了Python入門教程(二十)Python的Lambda表達式,lambda表達式是一行的函數(shù)。它們在其他語言中也被稱為匿名函數(shù),lambda表達式非常有用,可以讓代碼簡單,簡潔,需要的朋友可以參考下2023-04-04
Python實現(xiàn)使用request模塊下載圖片demo示例
這篇文章主要介紹了Python實現(xiàn)使用request模塊下載圖片,結(jié)合完整實例形式分析了Python基于requests模塊的流傳輸文件下載操作相關實現(xiàn)技巧,需要的朋友可以參考下2019-05-05
python實現(xiàn)對求解最長回文子串的動態(tài)規(guī)劃算法
這篇文章主要為大家詳細介紹了python實現(xiàn)對求解最長回文子串的動態(tài)規(guī)劃算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
Python?matplotlib繪制散點圖配置(萬能模板案例)
這篇文章主要介紹了Python?matplotlib繪制散點圖配置(萬能模板案例),散點圖是指在??回歸分析???中,數(shù)據(jù)點在直角坐標系平面上的?分布圖???,散點圖表示因變量隨??自變量???而?變化???的大致趨勢,據(jù)此可以選擇合適的函數(shù)??對數(shù)???據(jù)點進行?擬合2022-07-07

