Using the Select module in Python to implement Non-blocking Io_python

Source: Internet
Author: User

The original meaning of the socket is "hole" or "socket". As a BSD Unix process communication mechanism, take the latter meaning. Often referred to as "sockets," used to describe IP addresses and ports, is a handle to a communication chain. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and is bound to a port where different ports correspond to different services. Socket as its English intended, like a porous socket. A host is like a room full of sockets, each socket has a number, and some outlets provide 220 volts AC, some provide 110 volts AC, and some provide cable TV programs. Customer software will plug into different number of sockets, you can get different services. -Baidu Encyclopedia

Socket is so important, today's network programming is almost all used it, it originated in Unix, and unix/linux one of the basic philosophy is "All Files", can be opened, read-write, closed mode to operate. However, for network services, often targeted at a large number of customer groups, such as the web, for such services, it is necessary to ensure that both the request can be processed in parallel, but also to ensure the stability of services. But the traditional socket in the processing of concurrency is deficient, with the help of the Select module, it is better to non-blocking io.

The Select module in Python accepts four parameters in a list, which is a readable file object that needs to be monitored, a writable file object, an exception file object, and a time-out setting, and when a monitored object changes, the Select Returns a list of objects that have changed. Here's a simple chat room with select:

#!/usr/bin/env python #*-* coding:utf-8 *-* import socket Import Select Import SYS import signal class chatserver (): De F __init__ (self,host,port,timeout=10,backlog=5): #记录连接的客户端数量 self.clients =0 #存储连接的客户端socket和地址对应的字典 self. clientmap={} #存储连接的客户端socket self.outputs = [] #建立socket self.server=socket.socket (socket.af_inet,socket.s Ock_stream) self.server.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) Self.server.bind ((Host,port)) Self.server.listen (backlog) #增加信号处理 signal.signal (Signal.sig Int,self.sighandler def sighandler (self): Sys.stdout.write ("Shutdown server......\n") #向已经连接客户端发送关系信息, and actively shut down the SOC Ket for output in Self.outputs:output.send ("Shutdown Server") output.close () #关闭listen Self.serve R.close () Sys.stdout.flush () #主函数, to start server def run (self): #需要监听的可读对象 Inputs=[self.server] Runing=t Rue #添加监听主循环 while Runing:try:readable,writeable,exceptionAl = Select.select (inputs,self.outputs,[]) #此处会被select模块阻塞, the Select returns except Select.error,e only if the three parameters that are listening are changed:
        The break #当返回的readable中含有本地socket的信息时 indicating that a client is requesting a connection if self.server in readable: #接受客户端连接请求 Client,addr=self.server.accept () sys.stdout.write ("New Connection from%s\n"%str (addr)) Sys.stdout.flush () #更新服务器上客户端连接情况 #1, add 1 #2, self.outputs Add a column of #3, Self.clientmap adds a pair of #4, adds readable to input Monitoring self.clients + 1 self.outputs.append (client) self.clientmap[client]=addr Inputs.append
        (client) #readable中含有已经添加的客户端socket, and readable #说明 1, the client has data sent over or 2, the client requests to close Elif Len (readable)!= 0: #1, remove the socket csock=readable[0 in this list] #2, according to this socket, in the clientmap stored in advance, remove the client's address, the details of the port Host,p
          ORT = Self.clientmap[csock] #3, fetching data, or accepting shutdown requests, and handling #注意, this operation is blocked, but because the data is cached locally, the speed is very fast try: data = CSOCK.RECV (1024). Strip () for CS in Self.outputs:if CS!= csock:cs.send ("%s\n"%data) except
          Socket.error,e:self.clients-= 1 inputs.remove (csock) self.outputs.remove (Csock) Del Self.clientmap[csock] #print self.outputs self.server.close () if __name__ = = "__main__": Chat=cha

 Tserver ("", 8008) Chat.run ()

Run this script, and then connect 8008 ports with any client such as Telnet or netcat, and a conversation can take place between multiple clients.

In fact, the Select module itself is blocked, when the need to monitor the socket changes, select to return, the following program will continue to execute, the program based on the return value of select, the various cases are processed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.