Cara menggunakan socket listen method python

Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It’s not really a tutorial - you’ll still have work to do in getting things operational. It doesn’t cover the fine points [and there are a lot of them], but I hope it will give you enough background to begin using them decently.

Sockets

I’m only going to talk about INET [i.e. IPv4] sockets, but they account for at least 99% of the sockets in use. And I’ll only talk about STREAM [i.e. TCP] sockets - unless you really know what you’re doing [in which case this HOWTO isn’t for you!], you’ll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I’ll start by talking about blocking sockets. You’ll need to know how they work before dealing with non-blocking sockets.

Part of the trouble with understanding these things is that “socket” can mean a number of subtly different things, depending on context. So first, let’s make a distinction between a “client” socket - an endpoint of a conversation, and a “server” socket, which is more like a switchboard operator. The client application [your browser, for example] uses “client” sockets exclusively; the web server it’s talking to uses both “server” sockets and “client” sockets.

History

Of the various forms of IPC, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town.

They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the internet. With good reason — the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy [at least compared to other schemes].

Creating a Socket

Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following:

# create an INET, STREAMing socket
s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# now connect to the web server on port 80 - the normal http port
s.connect[["www.python.org", 80]]

When the connect completes, the socket s can be used to send in a request for the text of the page. The same socket will read the reply, and then be destroyed. That’s right, destroyed. Client sockets are normally only used for one exchange [or a small set of sequential exchanges].

What happens in the web server is a bit more complex. First, the web server creates a “server socket”:

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]

A couple things to notice: we used socket.gethostname[] so that the socket would be visible to the outside world. If we had used s.bind[['localhost', 80]] or s.bind[['127.0.0.1', 80]] we would still have a “server” socket, but one that was only visible within the same machine.

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
0 specifies that the socket is reachable by any address the machine happens to have.

A second thing to note: low number ports are usually reserved for “well known” services [HTTP, SNMP etc]. If you’re playing around, use a nice high number [4 digits].

Finally, the argument to

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
1 tells the socket library that we want it to queue up as many as 5 connect requests [the normal max] before refusing outside connections. If the rest of the code is written properly, that should be plenty.

Now that we have a “server” socket, listening on port 80, we can enter the mainloop of the web server:

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]

There’s actually 3 general ways in which this loop could work - dispatching a thread to handle

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
2, create a new process to handle
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
2, or restructure this app to use non-blocking sockets, and multiplex between our “server” socket and any active
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
2s using
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
5. More about that later. The important thing to understand now is this: this is all a “server” socket does. It doesn’t send any data. It doesn’t receive any data. It just produces “client” sockets. Each
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
2 is created in response to some other “client” socket doing a
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
7 to the host and port we’re bound to. As soon as we’ve created that
# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
2, we go back to listening for more connections. The two “clients” are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends.

IPC

If you need fast IPC between two processes on one machine, you should look into pipes or shared memory. If you do decide to use AF_INET sockets, bind the “server” socket to

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]
9. On most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster.

See also

The integrates cross-platform IPC into a higher-level API.

Using a Socket

The first thing to note, is that the web browser’s “client” socket and the web server’s “client” socket are identical beasts. That is, this is a “peer to peer” conversation. Or to put it another way, as the designer, you will have to decide what the rules of etiquette are for a conversation. Normally, the connecting socket starts the conversation, by sending in a request, or perhaps a signon. But that’s a design decision - it’s not a rule of sockets.

Now there are two sets of verbs to use for communication. You can use

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
2 and
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3, or you can transform your client socket into a file-like beast and use
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
4 and
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
5. The latter is the way Java presents its sockets. I’m not going to talk about it here, except to warn you that you need to use
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
6 on sockets. These are buffered “files”, and a common mistake is to
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
5 something, and then
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
4 for a reply. Without a
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
6 in there, you may wait forever for the reply, because the request may still be in your output buffer.

Now we come to the major stumbling block of sockets -

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
2 and
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3 operate on the network buffers. They do not necessarily handle all the bytes you hand them [or expect from them], because their major focus is handling the network buffers. In general, they return when the associated network buffers have been filled [
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
2] or emptied [
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3]. They then tell you how many bytes they handled. It is your responsibility to call them again until your message has been completely dealt with.

When a

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3 returns 0 bytes, it means the other side has closed [or is in the process of closing] the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I’ll talk more about this later.

A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That’s it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes.

But if you plan to reuse your socket for further transfers, you need to realize that there is no EOT on a socket. I repeat: if a socket

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
2 or
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3 returns after handling 0 bytes, the connection has been broken. If the connection has not been broken, you may wait on a
while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]
3 forever, because the socket will not tell you that there’s nothing more to read [for now]. Now if you think about that a bit, you’ll come to realize a fundamental truth of sockets: messages must either be fixed length [yuck], or be delimited [shrug], or indicate how long they are [much better], or end by shutting down the connection. The choice is entirely yours, [but some ways are righter than others].

Assuming you don’t want to end the connection, the simplest solution is a fixed length message:

class MySocket:
    """demonstration class only
      - coded for clarity, not efficiency
    """

    def __init__[self, sock=None]:
        if sock is None:
            self.sock = socket.socket[
                            socket.AF_INET, socket.SOCK_STREAM]
        else:
            self.sock = sock

    def connect[self, host, port]:
        self.sock.connect[[host, port]]

    def mysend[self, msg]:
        totalsent = 0
        while totalsent 

Bài mới nhất

Chủ Đề