SoFunction
Updated on 2024-10-30

python network programming study notes (I)

Study Book: Fundamentals of Python Network Programming by John Goerzen

Part I Underlying Network Learning

Python provides all the methods for accessing the underlying operating system's socket interfaces, which provide flexible and powerful functionality when needed.

(1) Basic client operation

In the book Fundamentals of Python Network Programming, the author lists a simple Python client program as follows:

Copy Code The code is as follows.

import socket,sys
port =70
host=[1]

filename=[2]

s=(socket.AF_INET,socket.SOCK_STREAM)
((host,port))

(filename+"\r\n")

while 1:
    buf=(2048)
    if not len(buf):
        break
    (buf)

This program implements the Gopher protocol to realize the function of requesting relevant documents from a host. (Gopher is a very famous information finding system on the Internet, it will Internet documents organized into some kind of index, it is very convenient to bring the user from one place on the Internet to another place. Before the emergence of the WWW, Gopher is the most important information retrieval tool on the Internet, Gopher site is also the most important site. But after the emergence of the WWW, Gopher lost its former glory. Now it is rarely used.)
So I did a little test following the statements in the book, running python under dos . But the system prompts as

Traceback (most recent call last):
File "", line 5, i
filename=[2]
IndexError: list index out of range

Looking at it, there are only two elements ['', '/'] so filename=[2] is out of the lower bound. But why is this the reason? Is it a mistake in the book, because I am also a beginner in socket, not very understanding, so I also did not find the reason, if any of the big cow know what is the reason, I hope to give an explanation.

(2) Basic server operations
A simple server program is also given in the book Fundamentals of Python Network Programming as follows:

Copy Code The code is as follows.

import socket
host=''
port=51423
s=(socket.AF_INET,socket.SOCK_STREAM,0)
(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
((host,port))
(1)

print "Server is running on port %d;press Ctrl-C to terminate." %port
while 1:
    clientsock,clientaddr=()
    clientfile=('rw',0)
    ("welcome,"+str(clientaddr)+'\n')
    ("Please enter a string:")
    line=().strip()
    ("You entered %d characters.\n" %len(line))
    ()
    ()

After the program runs, it prompts "Server is running on port 51423: press Ctrl-C to terminate". At this time, through another machine telnet this machine port 51423, such as telnet 127.0.0.1:51423, this time will prompt welcome 127.0.0.1 ****,please enter a string:. Then enter a few characters, it will return the number of characters you entered.

Here is a little analysis of the program:

1, first of all, import the socket module, to the host and port value.
2, call () to create a socket assignment to s. (domain, type, protocol). domain parameter values are AF_UNIX, AF_LOCAL, AF_INET, PF_UNIX, PF_LOCAL, PF_INET. these values in the AF_UNIX = AF_LOCAL, PF AF_UNIX=AF_LOCAL, PF_UNIX=PF_LOCAL, AF_LOCAL=PF_LOCAL, and AF_INET=PF_INET. Generally speaking, AF represents the ADDRESS FAMILY address family, and PF represents the PROTOCOL FAMILY protocol family, but the two macros are the same, so it doesn't matter which one you use. The type parameter specifies the type of socket: SOCK_STREAM provides ordered, reliable, bi-directional, and connection-based byte streaming. sock_dgram supports datagrams. sock_seqpacket provides ordered, reliable, bi-directional, and connection-based datagram communication. sock_raw provides access to the original network protocols. sock_rdm provides reliable datagram layers, but the protocol family is the same, so it doesn't matter which one you use. SOCK_RDM provides a reliable datagram layer, but does not guarantee ordering. protocol is generally taken as 0 (I haven't figured out why it's taken as 0, so I'll put it in the future when I understand it).
3, (socket.SOL_SOCKET,socket.SO_REUSEADDR,1). setsockopt() function is used to set the option value for any type of arbitrary state socket interface. Although options exist at different protocol levels, this function only defines options at the highest "socket" level. Options affect the operation of the socket interface, such as whether expedited data is received in the normal data stream, whether broadcast data can be sent from the socket interface, and so on. The first parameter in this function is a protocol level parameter that specifies 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 layer options
SOL_TCP to access TCP layer options
The second parameter corresponds to the first parameter. The first parameter determines the protocol layer level, and the second parameter determines the combination of options under that protocol layer.The combination of options for SOL_SOCKET is 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 specific uses of the combination can be found at: /view/
The third parameter is set to 1. I don't really understand the meaning here, I tried to change 1 to 50 and the result is the same. I tried replacing 1 with 50, and the result was the same. Replacing it with 0 also works, and I didn't find any difference. I hope that the experts to give guidance.
4. ((host,port)) binds the host port.
5.(1): The listen function uses an active connection socket to become a passive connection socket, allowing a process to accept requests from other processes, thus becoming a server process. In TCP server programming listen function turns a process into a server and specifies the corresponding socket to become a passive connection. The parameters here involve some networking details. While the process is processing one connection request after another, there may be other connection requests. Because a TCP connection is a process, there may be a half-connection state, where the server process cannot complete the connection request fast enough because too many users are trying to connect at the same time. If this situation arises, what does the server process expect the kernel to do? The kernel maintains a queue in its own process space to keep track of connections that are completed but the server process has not yet taken over or is in the process of connecting, such a queue the kernel can not make it arbitrarily large, so there must be an upper limit on the size. This backlog tells the kernel to use this value as the upper limit. Undoubtedly, the server process can't just specify a value; the kernel has a permissible range. This range is implementation dependent. It's hard to have some kind of uniformity, and generally this value will be 30 or less. Here, a value of 1 means that at most one connection is 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 pieces of information, a new connection to the client socket and the client's ip address and port number. If you add a print statement to the above example to output clientsock and clientaddr, you will see that clientsock is,clientaddr=('Client Ip',port). The file class object is used in a later loop, the server then displays some introductory information, reads a string from the client, displays an answer, and finally closes the client socket.