Python Select and socket with basic learning, is the Python standard library example

Source: Internet
Author: User

#-*-Coding:utf-8-*-

# python:2.x

__author__ = ' Administrator '

Import Select,socket,sys,queue

# function: A notification that waits for input or the output channel is ready

#select io monitoring function, portable interface is posix function select (), Unix and windows all support this function, poll () Span style= "font-family: the song Body;" > only unix, There are some for unix specific variant options

#select () is the underlying operating system implementation of a direct interface that monitors sockets, opens files and pipelines (can be any filen () method Object, it returns a valid file descriptor), which is readable, writable, Or a communication error occurs,Select () can efficiently monitor multiple connections at the same time

#select () server-side Example Learning

Serve=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Serve.setblocking (0) # If the socket is 0, set to non-blocking , blocking mode

serer_address= (' localhost ', 10000)

Print >>sys.stderr, ' Starting up on%s port%s '%serer_address

Serve.bind (serer_address)

Serve.listen (5)

"""

Select () prototype Yes (Rlist,wlist,xlist[,timeout])

Rlist waits for the object to be read,wlist waits for the final object , xlist waits for the exception object, the last optional object, specifies the wait time, the unit is s, The Select () method returns the value of the prepared object is ternary, if No object is ready in timeout time, then the return value is empty list

"""

inputs=[serve]# Read

outputs=[]# Write

# The server main loop adds or deletes connections to these lists, because the version server waits for a socket to become writable (not immediately) before sending the data, so each output connection needs a queue as the data buffer sent through the socket

message_queues={}

# The main part of the server program is looping, calling Select () to block, and waiting for network activity

While inputs:

Print >>sys.stderr, ' Waiting for the next event '

Readable,writable,exceptional=select.select (inputs,outputs,inputs)

# readable sockets represent 3 Possible scenarios, if the socket is the primary server socket, which is the socket used to listen for connections, meaning it is ready to accept another incoming connection, in addition to adding new connections to the list of inputs to be monitored, This section also sets the client to non-blocking

For s in readable:

If S is serve:

Connectiuon,client_addre=s.accept ()

Print >>sys.stderr, ' connection from ', Client_addre

Connectiuon.setblocking (0)

Inputs.append (Connectiuon)

Message_queues[connectiuon]=queue.queue ()

# The next situation is already connected, the customer has sent the data, the data is read using recv () , and then rotated in the queue, to return

Else

DATA=S.RECV (1024)

If data:

Print >>sys.stderr, ' received%s form%s '% (Data,s.getpeername ())

Message_queues[s].put (data)

If s not in outputs:

Outputs.append (s)

# No data available readable sockets from disconnected end, can close stream

Else

Print >>sys.stderr, ' closeing ', Client_addre

If s in outputs:

Outputs.append (s)

Inputs.append (s)

S.close ()

Del Message_queues[s]

# for writable connections, the situation is less, if there is data in a connection queue, send the next message, otherwise, the connection is removed from the output connection, the next cycle , select () no longer indicates that the socket is ready to send data

For S in writable:

Try

Next_msg=message_queues[s].get_nowait ()

Except Queue.empty:

Print >>sys.stderr, ', S.getpeername (), ' Queue empty '

Outputs.remove (s)

Else

Print >>sys.stderr, ' sending%s to%s '% (Next_msg,s.getpeername ())

S.send (NEXT_MSG)

# Finally, if a socket has an error, close

For S in exceptional:

Print >>sys.stderr, ' exception condition on ', S.getpeername ()

Inputs.remove (s)

If s in outputs:

Outputs.remove (s)

S.close ()

#select () client program

Message=[' This is the message ', ' It'll be sent, '

' In parts. '

serer_address= (' localhost ', 10000)

Socks=[socket.socket (Socket.af_inet,socket. SOCK_STREAM),

Socket.socket (Socket.af_inet,socket. SOCK_STREAM),]

Print >>sys.stderr, ' Connection to%s and%s '% (serer_address)

For s in socks:

S.connect (serer_address)

# send information once through each socket, write new data, and then get all the corresponding data

For m in message:

If s in socks:

Print >>sys.stderr, '%s:sending%s '% (S.getsockname (), M,s.send (m))

For s in socks:

DATA=S.RECV (1024)

print '%s:%s '% (S.getpeername (), data)

If not data:

Print >>sys.stderr, ' closeing socket ', S.getsockname ()

S.close ()

Python Select and socket with basic learning, is the Python standard library example

Related Article

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.