开发者

blocking sockets and select

开发者 https://www.devze.com 2023-02-13 11:34 出处:网络
i\'m playing around with sockets, and I\'m having some doubts about using blocking sockets with select.Let\'s assume i\'m only tracking potential readers.Am I right in thinking that select will go thr

i'm playing around with sockets, and I'm having some doubts about using blocking sockets with select.Let's assume i'm only tracking potential readers. Am I right in thinking that select will go through the first socket in the list and if some data is available it will return and if not it will block until select's timeout expires? When will the other sockets in the read list be checked by select?

Let me illustrate with a python example for simplicity:

servsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
servsock.bind(("", 2500))
servsock.listen(15)
servsock.setblocking(1)

readlist = [servsock]

while 1:
    (sread, swrite, sexc) =  select.select(readlist, [], [] ); 

    for sock in sread:

        #received a connect to the server socket
        if  sock == servsock:

        (newsock, address) = servsock.accept()
            newsock.setblocking(1)
            print "I got a connection from ", address
            readlist.append(newsock)
         开发者_运维知识库   newsock.send("you're connected to the select server")
        else:
            recv_msg = sock.recv(5)

            if recv_msg == "":
                (host, port) = sock.getpeername()
                print "Client %s:%s closed the connection" % (host,port)
                sock.close()
                readlist.remove(sock)
            else:
                (host, port) = sock.getpeername()
                print "client %s:%s sent: %s "% (host,port,recv_msg)

Since they're blocking sockets, will select always block when testing to see if the socket in the list has data to read?


The select() C API returns a list of all sockets that are currently readable. Assuming python's wrapper does the same, sread will contain multiple elements if multiple sockets are readable.

A blocking socket will only block if there is no data present, so after a select() call indicated there is data, you can assume that one call to recv will not block.


select() will block until one of the sockets has data. It doesn't check only the first one, it checks everything in your readlist variable.

In for sock in sread: it iterates through all the sockets that have data to be read.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号