歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python使用select實現異步通信

Python使用select實現異步通信

日期:2017/3/1 9:48:08   编辑:Linux編程

當一個服務器需要與多個客戶端進行通信時,可以使用多進程或者多線程的服務器,也可以使用select模塊,它可以實現異步通信。Python中的select模塊包含了poll()和select(),select的原型為(rlist,wlist,xlist[,timeout]),其中rlist是等待讀取的對象,wlist是等待寫入的對象,xlist是等待異常的對象,最後一個是可選對象,指定等待的時間,單位是s. select()方法的返回值是准備好的對象的三元組,若在timeout的時間內,沒有對象准備好,那麼返回值將是空的列表。

下面是使用select的服務器:

#!/usr/bin/env python
import socket,select
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.bind(('',10000))
server.listen(5)
inputs=[server]
while 1:
rs,ws,es=select.select(inputs,[],[],1)
for r in rs:
if r is server:
clientsock,clientaddr=r.accept();
inputs.append(clientsock);
else:
data=r.recv(1024);
if not data:
inputs.remove(r);
else:
print data

再編寫客戶端程序,就可以測試select服務器了,客戶端代碼為:

#!/usr/bin/env python
import socket
host='127.0.0.1';
port=10000;
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.send('hello from client')
s.close();

poll實現服務器時,需要用到register()和unregister()方法,作用是加入和移除對象,poll()的返回值包括了文件描述符和事件,polling的事件常量有POLLIN,POLLPRI,POLLPOUT,POLLERR,POLLHUP,POLLVAL,分別表示讀取數據,讀取緊急數據,文件描述符已經准備好,文件描述符出錯,連接丟失,無效請求。

下面是使用poll的服務器程序:

#!/usr/bin/env python
import socket,select
s=socket.socket()
host=""
port=10000
s.bind((host,port))
fdmap={s.fileno():s}
s.listen(5)
p=select.poll()
p.register(s.fileno(),select.POLLIN|select.POLLERR|select.POLLHUP)
while 1:
events=p.poll(5000)
if len(events)!=0:
if events[0][1]==select.POLLIN:
sock,addr=s.accept()
buf=sock.recv(8196)
if len(buf)!=0:
print buf
sock.close()
print "no data"

再編寫客戶端程序,即可以測試服務器程序,客戶端為:

#!/usr/bin/env python
import socket
port=10000
s=socket.socket()
host=socket.gethostname()
s.connect((host,port))
s.send("hello from the client")
s.close()

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved