Python network programming study notes of one

  • 2020-04-02 13:44:03
  • OfStack

Learning book: the basics of python web programming by John Goerzen

The first part of the underlying network learning

              Python provides full access to the underlying operating system Socket interfaces, which can provide flexible and powerful functionality when needed.

(1) basic client operation

              In the book python network programming basics, the author lists a simple python client program as follows:


import socket,sys
port =70
host=sys.argv[1]
filename=sys.argv[2]
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.sendall(filename+"rn")
while 1:
    buf=s.recv(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)

The program is a Gopher protocol, from the host to request the function of relevant documents. Gopher is a very famous information search system on the Internet. It organizes the files on the Internet into some kind of index and easily takes users from one part of the Internet to another. Before the WWW, Gopher was the main information retrieval tool on the Internet, and Gopher site was also the main site. But with the advent of the WWW, Gopher lost its former glory. It is rarely used nowadays.)
            So I ran a test with the statements in the book, running python gopherclient.py quux.org on DOS. But the system prompts for

Traceback (most recent call last):
File "gopherclient.py", line 5, I
Filename = sys. Argv [2]
IndexError: list index out of range

At a glance, sys.argv has only two elements ['gopherclient.py', 'quux.org/'] so filename=sys.argv[2] is out of the lower bound. But why? Is it wrong in the book? Because I am also a beginner of socket and not very familiar with it, so I have not found the reason. If anyone knows the reason, I hope you can explain it.

(2) basic server operations
              The book python network programming basics also gives a simple server program, as follows:


import socket
host=''
port=51423
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM . 0)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)
print "Server is running on port %d;press Ctrl-C to terminate." %port
while 1:
    clientsock,clientaddr=s.accept()
    clientfile=clientsock.makefile('rw',0)
    clientfile.write("welcome,"+str(clientaddr)+'n')
    clientfile.write("Please enter a string:")
    line=clientfile.readline().strip()
    clientfile.write("You entered %d characters.n" %len(line))
    clientfile.close()
    clientsock.close()

When the program runs, it prompts "Server is running on port 51423:press ctrl-c to terminate." At this point, port 51423 of the local machine, Telnet 127.0.0.1:51423, will prompt welcome 127.0.0.1 **** from another machine,please enter a string:. After typing a few characters, it returns the number of characters you typed.

Here is an analysis of the program:

1. First, import socket module and assign values to host and port.
2. Call socket.socket () to set up a socket assignment to s. Socket. socket(domain, type, protocol). The values of the domain parameters are AF_UNIX,AF_LOCAL,AF_INET,PF_UNIX,PF_LOCAL,PF_INET. AF_UNIX=AF_LOCAL, PF_UNIX=PF_LOCAL, AF_LOCAL=PF_LOCAL, AF_INET=PF_INET. In general, AF represents the ADDRESS FAMILY ADDRESS FAMILY and PF the PROTOCOL FAMILY ADDRESS FAMILY, but the two macro definitions are the same, so it doesn't matter which one you use. Parameter type specifies the type of socket: SOCK_STREAM provides an ordered, reliable, bidirectional, and connection-based stream of bytes. SOCK_DGRAM supports datagram. SOCK_SEQPACKET provides orderly, reliable, bidirectional and connection-based datagram communication. SOCK_RAW provides access to the original network protocol. SOCK_RDM provides a reliable datagram layer, but does not guarantee orderliness. Protocol always takes 0 (I don't know why, but I'll write it down later if I understand).
3, s.s etsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1). The setsockopt() function is used to set the option values for any type, any state sleeve interface. Although options exist at different protocol levels, this function only defines options at the highest "nested interface" level. Options affect the operations of the jacket interface, such as whether urgent data is received in a normal data stream, whether broadcast data can be sent from the jacket interface, and so on. In this function, the first parameter is the protocol layer parameter, indicating the protocol stack where you want to access an option. Usually we need to use one of the following:
SOL_SOCKET to access the socket interface layer option
SOL_TCP to access the TCP layer options
The second parameter corresponds to the first parameter. The first parameter determines the level of the protocol layer, and the second parameter determines the combination of options under the protocol layer. The options for SOL_SOCKET are grouped as follows:
Protocol layer option name
SOL_SOCKET SO_REUSEADDR
SOL_SOCKET SO_KKEPALIVE
SOL_SOCKET SO_LINGER
SOL_SOCKET SO_BROADCAST
SOL_SOCKET SO_OOBINLINE
SOL_SOCKET SO_SNDBUF
SOL_SOCKET SO_RCVBUF
SOL_SOCKET SO_TYPE
SOL_SOCKET SO_ERROR
Some of the specific combination usage: http://wenku.baidu.com/view/23013b7101f69e3143329402.html
The third parameter is 1, and I don't really understand what that means here, so I'm trying to replace 1 with 50, and it's the same thing. I could have done it with a 0, but I didn't see any difference. I hope you give guidance.
4. S.ind ((host,port)) binds the host port.
5. S.isten (1) : the listen function USES the active connection sleeve interface to become the connected sleeve interface, enabling a process to accept requests from other processes, thus becoming a server process. In TCP server programming the listen function turns a process into a server and specifies that the corresponding socket becomes a passive connection. The parameters here involve some network details. While the process is processing one connection request at a time, there may be other connection requests. Because TCP connections are a process, there can be a semi-connected state, and sometimes the server process cannot complete connection requests quickly because too many users are trying to connect at the same time. If this happens, what does the server process want the kernel to do with it? The kernel maintains a queue in its own process space to keep track of completed connections, but the server process has not yet taken over or is in progress. Such a queue kernel cannot be arbitrarily large, so there must be an upper limit on the size. The backlog tells the kernel to use this value as the upper limit. There is no doubt that server processes cannot specify arbitrary values, and the kernel has a range of permissions. This scope is implementation dependent. It's very difficult to have some kind of uniformity, and in general this value is less than 30. Setting this to 1 means that there is at most one connection waiting to be processed at a time.
6. The while loop starts with the accept() function. The program closes the socket after connecting to a client. When a client connects, accept returns two messages, a new connection to the client socket and the client's IP address and port number. As in the example above add print statements output clientsock and clientaddr, you will find clientsock for socket. Socketobject, clientaddr = (' client Ip, port). The following loop USES a file class object, and the server then displays some introductory information, reads a string from the client, displays a reply, and finally closes the client socket.


Related articles: