Python network programming learning notes (1)

Source: Internet
Author: User
Tags gopher

Learning book: John Goerzen, author of python network programming Basics

Part 1 underlying network learning

Python provides all the methods to access the Socket interface of the underlying operating system. These interfaces can provide flexible and powerful functions when needed.

(1) Basic client operations

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

Copy codeThe Code is 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 + "\ r \ n ")

While 1:
Buf = s. recv (2048)
If not len (buf ):
Break
Sys. stdout. write (buf)

This program implements the Gopher protocol to request relevant documents from the host. (Gopher is a well-known information search system on the Internet. It organizes files on the Internet into some index, so that users can easily take one from the Internet to another. Before the emergence of WWW, Gopher was the most important information retrieval tool on the Internet, and the Gopher site was also the most important site. However, after the emergence of WWW, Gopher lost its glory. Currently, it is rarely used .)
So I ran the test according to the statement in the book and ran python gopherclient. py quux.org under dos. However, the system prompts

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

After reading this, sys. argv only has two elements: ['gopherclient. py', 'quux. org/']. Therefore, filename = sys. argv [2] is beyond the lower bound. But why? Is it wrong in the book, because I am also a beginner socket, not very familiar with, so I did not find the reason, if any Daniel knows what the reason is, I hope to explain it.

(2) Basic server operations
Python network programming basics also provides a simple server program as follows:

Copy codeThe Code is 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 ()

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

The program is analyzed here:

1. First import the socket module and assign values to the host and port.
2. Call socket. socket () to create a socket and assign it to s. The socket. socket (domain, type, protocol). domain parameter values include AF_UNIX, AF_LOCAL, AF_INET, PF_UNIX, PF_LOCAL, and PF_INET. AF_UNIX = AF_LOCAL, PF_UNIX = PF_LOCAL, AF_LOCAL = PF_LOCAL, AF_INET = PF_INET. In general, AF indicates the address family, and PF indicates the protocol family, but the two macros are the same, so it does not matter which one is used. The parameter type specifies the socket type. SOCK_STREAM provides ordered, reliable, bidirectional, and connection-based byte streams. SOCK_DGRAM supports datagram. SOCK_SEQPACKET provides ordered, 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 is generally set to 0 (why I have not figured out why to get 0? I will try again later ).
3. s. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1 ). The setsockopt () function is used to set the option values of interfaces of any type and any status. Although there are options on different protocol layers, this function only defines the options at the highest "set interface" level. This option affects operations on the set interface, such as whether the expedited data is received in a common data stream, and whether the broadcast data can be sent from the set interface. In this function, the first parameter is the protocol layer parameter, indicating the protocol stack where an option is to be accessed. We usually need to use one of the following:
SOL_SOCKET to access the interface 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 Option combination under the protocol layer. The options of SOL_SOCKET are combined 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
Specific combination usage visible: http://wenku.baidu.com/view/23013b7101f69e3143329402.html
The third parameter is set to 1, and I don't quite understand the meaning here. I tried to replace 1 with 50, and the result is the same. It is also possible to change to 0 without any difference. Hope you can give me some advice.
4. s. bind (host, port) to bind the host port.
5. s. listen (1): The listen function converts an active connection sleeve interface into a connection sleeve interface, so that a process can accept requests from other processes and become a server process. In TCP Server programming, the listen function converts a process into a server and specifies a socket to a passive connection. The parameters here involve some network details. When a process processes a connection request, other connection requests may exist. Because TCP connection is a process, there may be a semi-connection status. Sometimes, due to too many users trying to connect at the same time, the server process cannot quickly complete the connection request. If this happens, what does the server process want the kernel to do? The kernel maintains a queue in its own process space to track the established connections, but the server process has not taken over the processing or ongoing connections, such a queue kernel cannot be arbitrarily large, so there must be an upper limit of the size. This backlog tells the kernel to use this value as the upper limit. There is no doubt that the server process cannot specify a value at will, and the kernel has a permitted range. This range is implementation-related. It is difficult to have a certain degree of uniformity. Generally, this value is smaller than 30. If this parameter is set to 1, only one connection is waiting for processing at most.
6. The while loop starts with the accept () function. The program closes the socket after connecting to a client. When a client is connected, accept returns two messages: the IP address and port number of the new socket Client and the client. As shown in the preceding example, if you add the print statement to output clientsock and clientaddr, you will find that clientsock is socket. socketobject, clientaddr = ('client ip', port ). The following loop uses a file object. The server then displays some introductory information, reads a string from the client, displays a response, and closes the client socket.

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.