Python Network Programming Learning Notes (i) _python

Source: Internet
Author: User
Tags gopher

Learning book: "The Basics of Python network Programming" by John Goerzen, author

The first part of the bottom network learning

Python provides all the means to access the socket interface of the underlying operating system, and these interfaces can provide flexible and powerful functionality when needed.

(1) Basic client operation

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

Copy Code code 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 realizes the Gopher protocol, and realizes the function of requesting related documents from the host. (Gopher is a very well-known information lookup system on the Internet that organizes files on the Internet into some sort of index, easily bringing users from one place on the Internet to another.) Prior to the advent of WWW, Gopher was the most important information retrieval tool on the Internet, and the Gopher site was also the main site. But after the WWW appeared, Gopher lost the glory of the past. Now it is rarely used. )
So, I followed the statement on the book to test, in DOS run Python gopherclient.py quux.org. 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

Looked, SYS.ARGV only two elements [' gopherclient.py ', ' quux.org/'] so filename=sys.argv[2] went beyond the lower bound. But why does this happen? Is the book is wrong, because I am also a beginner socket, not very understanding, so I also did not find the reason, if Daniel know what the reason, I hope to give a lecture.

(2) Basic server operation
The Python network programming Basics also gives a simple server program, as follows:

Copy Code code 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)
Clientfile.close ()
Clientsock.close ()

After the program is run, prompt "Server is running on port 51423:press ctrl-c to terminate". At this point, telnet to the 51423 port of the machine via another machine, such as Telnet 127.0.0.1:51423, prompting welcome 127.0.0.1 ****,please Enter a string:. Then, after entering a few characters, you will return the number of characters you enter.

Here's an analysis of the program:

1, first import socket module, to host and port assignment value.
2, call Socket.socket () to create a socket assignment to S. Socket.socket (domain, type, protocol). The value of the domain parameter is af_unix,af_local,af_inet,pf_unix,pf_local,pf_inet. These values are af_unix=af_local, pf_unix=pf_local, Af_local=pf_local, af_inet=pf_inet. In general, AF represents the address FAMILY family of addresses, and PF represents the protocol FAMILY protocol family, but the two macro definitions are the same, so it doesn't matter which one you use. The parameter type specifies the type of the socket: Sock_stream provides an orderly, reliable, two-way, and concatenated byte stream. Sock_dgram supports datagrams. Sock_seqpacket provides an orderly, reliable, two-way, and connectionless datagram communication. Sock_raw provides access to the original network protocol. SOCK_RDM provides a reliable datagram layer, but does not guarantee order. Protocol generally take 0 (why take 0 I did not make it clear, put it in the future and then write it).
3, s.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1). The setsockopt () function is used for setting option values for any type, any state set interface. Although there are options on different protocol tiers, this function defines only the highest options on the "set interface" level. Options affect the operation of the socket interface, such as whether the expedited data is received in the normal data stream, whether the broadcast data can be sent from the socket, and so on. In this function, the first parameter is the protocol layer parameter, indicating the protocol stack on which you want to access an option. Usually we need to use one of the following:
Sol_socket to access the Set interface layer option
Sol_tcp to access the TCP layer option
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 Sol_socket options 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 usages are visible: http://wenku.baidu.com/view/23013b7101f69e3143329402.html
The third parameter is set to 1, and I'm not quite sure what it means here, I try to change 1 to 50, and the result is the same. It's OK to change to 0, and no difference is found. I hope Daniel will give you some pointers.
4, S.bind ((Host,port)) binding host port.
5, S.listen (1): The Listen function uses the active connection sleeve interface to become a connected socket, so that a process can accept requests from other processes, thus becoming a server process. In TCP server programming, the Listen function transforms a process into a server and specifies that the corresponding socket becomes a passive connection. The parameters here relate to some network details. When a process Nyaya a connection request, there may be other connection requests. Because a TCP connection is a process, there may be a partially connected state, sometimes because too many users are trying to connect at the same time, making the server process unable to complete the connection request quickly. If this happens, what does the server process want the kernel to do? The kernel will maintain a queue in its own process space to track these 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 a maximum size. This backlog tells the kernel to use this value as the upper limit. There is no doubt that the server process cannot arbitrarily specify a number, and the kernel has a permitted range. This scope is implementation-related. It is difficult to have some kind of unification, generally this value will be less than 30. This setting of 1 indicates that there is at most one pending connection at a time.
6, while loop starts with the Accept () function. The program closes the socket after a client is connected. When a client connects, accept returns two messages, a new connection to the client socket and the client's IP address and port number. If you add a print statement to output Clientsock and clientaddr in the example above, you will find Clientsock for socket.socketobject,clientaddr= (' client IP ', port). The following loop uses the file class object, and the server then displays some introductory information, reads a string from the client, displays an answer, and finally closes the client socket.

Related Article

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.