OK, first write the server segment of a Python socket for open three ports: in the case of 10000,10001,10002.krondo, each server binds a port, and the test requires 3 shells, respectively. Run separately. This is too much trouble to run these services separately with three thread.
Import optparse import OS import socket import time from threading import Thread import Stringio txt = ' ' 1111 2222 3333 4444 ' def server (listen_socket): While true:buf = Stringio.stringio (txt) sock, addr = Listen_socket.accept () print ' Somebody at%s wants poetry! '% (addr,) while True:try:line = Buf.readline (). Strip () if not line:sock.close () break Sock.sendall # This is a blocking call print ' send bytes to client:%s '% #sock. Close () except Soc Ket.error:sock.close () Break Time.sleep (1) #server和client连接后, the server intentionally waits one second after each word is sent and then sends another Word def main (): ports = [10000, 10001, 10002] for port in ports:listen_socket = Socket.socket (socket.af_i NET, Socket. SOCK_STREAM) listen_socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) addres = (str (' 127.0.0.1 '), port) ListEn_socket.bind (addres) Listen_socket.listen (5) print "Start Listen at:%s"% (port,) worker = Thread (target = Server, args = [Listen_socket]) Worker.setdaemon (True) Worker.start () if __name__ = = ' __main__ ': main () while True:time.sleep (0.1) #如果不sleep的话, the CPU is fully occupied by Python
The following is a client that does not use an asynchronous network to connect to this three-port server:
Import Socket
If __name__ = = ' __main__ ':
ports = [10000, 10001, 10002] for
port in ports: Address
= (Str (' 127.0.0.1 '), port
sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
sock.connect
poem = ' while
True:
data = SOCK.RECV (4)
if not data:
Sock.close ()
break
poem + + = data
The following is read with the asynchronous client, the following code:
Import datetime, errno, Optparse, select, Socket def connect (port): "" "Connect to the given server and return a No
n-blocking socket. "" " Address = (str (' 127.0.0.1 '), port) sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Sock.connect sock.setblocking (0) return sock def Format_address (address): Host, port
= Address return '%s:%s '% (host or ' 127.0.0.1 ', port) if __name__ = = ' __main__ ': ports = [10000, 10001, 10002] Start = Datetime.datetime.now () sockets = map (connect, ports) poems = Dict.fromkeys (sockets, ') # socket-&G T Accumulated Poem # socket-> task Numbers sock2task = Dict ([(S, i + 1) for I, S in enumerate (sockets)]) Ckets = List (sockets) # Make a copy while sockets: #运用select来确保那些可读取的异步socket可以立即开始读取IO #OS不停的搜索目前可以read的s Ocket, some words will return rlist rlist, _, _ = Select.select (sockets, [], []) for the sock in rlist:data = ' "while True:try:new_dATA = SOCK.RECV (1024) except Socket.error, e:if e.args[0] = = errno.
Ewouldblock:break Raise Else:if not New_data:break
Else:print new_data Data + + new_data Task_num = Sock2task[sock] If not data: Sockets.remove (sock) sock.close () print ' Task%d finished '% Task_num _FMT = Format_address (Sock.getpeername ()) msg = ' Task%d:got%d bytes of poetry from%s ' Print msg% (t Ask_num, Len (data), ADDR_FMT) Poems[sock] + + = data Elapsed = Datetime.datetime.now ()-Start print ' Got Poems in%s '% elapsed
The result is only 4 seconds to complete the read task. Efficiency is three times times that of just synchronizing the socket. There are two main points of asynchronous transformation to the client:
In synchronous mode, the client creates the socket separately, and in asynchronous mode, clients create all the sockets at the beginning.
Set the socket to asynchronous mode by "sock.setblocking (0)".
Return readable IO via the Select two of the UNIX system
The core is 26 lines and 29 lines. In particular, a select operation of 29 rows returns a list of the sockets to be read.