Python network programming learning notes (1)

Source: Internet
Author: User
Tags gopher

Reprint Please note: @ small Wuyi http://www.cnblogs.com/xiaowuyi

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 ClientProgram, As follows:

ImportSocket, sysport= 70Host= 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")While1: Buf= S. Recv (2048)If NotLen (BUF ):BreakSYS. 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:

 Import  Sockethost = ''  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.