Learning book: John Goerzen, author of the basics of Python network programming
The first part of the bottom network learning
Python provides all the methods to access the socket interface of the underlying operating system, which can provide flexible and powerful functionality when needed.
(1) Basic client operation
In the book The Basics of Python network programming, the author lists a simple Python client program, as follows:
Copy the 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)
The program implements the Gopher protocol, which implements the ability to request 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, which makes it easy to bring users from one place on the Internet to another.) Before the advent of WWW, Gopher is the most important information retrieval tool on the Internet, and the Gopher site is also the most important site. But after the advent of WWW, Gopher lost its former glory. It is rarely used now. )
So, I followed the book to test the sentence, under DOS run Python gopherclient.py quux.org. However, the system prompts
Traceback (most recent):
File "gopherclient.py", line 5, I
FILENAME=SYS.ARGV[2]
Indexerror:list index out of range
Looked at, SYS.ARGV only two elements [' gopherclient.py ', ' quux.org/'] so filename=sys.argv[2] went beyond the nether. But why does it come to this? Is it wrong in the book, because I am also a beginner socket, not very understanding, so I also did not find the reason, if any Daniel know what is the reason, I hope to explain.
(2) Basic server operation
A simple server program is also given in the book "Fundamentals of Python Network Programming", as follows:
Copy the 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 the 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 ("entered%d characters.\n"%len (line))
Clientfile.close ()
Clientsock.close ()
After the program runs, it prompts "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, and you will be prompted welcome 127.0.0.1 ****,please Enter a string:. After entering a few characters, you will return the number of characters you have entered.
Here's an analysis of the program:
1. First import the socket module and assign the value to host and port.
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 in Af_unix=af_local, pf_unix=pf_local, Af_local=pf_local, af_inet=pf_inet. In general, AF means address FAMILY, PF represents protocol FAMILY protocol family, but the two macro definitions are the same, so it doesn't matter which one is used. Parameter type specifies the type of socket: Sock_stream provides an ordered, reliable, bidirectional, and connection-based byte stream. Sock_dgram supports datagrams. Sock_seqpacket provides an 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 order. Protocol generally take 0 (why take 0 I do not know, put in later understand and write it again).
3, s.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1). The setsockopt () function is used for setting option values of any type, any state socket interface. Although there are options on different protocol tiers, this function only defines the highest option on the "set interface" level. Options affect the operation of the socket, 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, which indicates 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 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 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 here I do not quite understand the meaning, I try to change 1 to 50, the result is the same. Change to 0 is also possible, did not find any difference. I hope Daniel will give you some advice.
4, S.bind ((Host,port)) binds the host port.
5, S.listen (1): The Listen function uses the active connection socket interface to become a connected socket interface, 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. There may be other connection requests when the process Nyaya one connection request. Because a TCP connection is a process, there may be a semi-connected state, and sometimes the server process cannot complete a connection request quickly because there are too many users trying to connect at the same time. 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 these completed connections, but the server process has not yet taken over the processing or ongoing connection, so a queue kernel cannot be arbitrarily large, so there must be a size limit. This backlog tells the kernel to use this value as the upper limit. There is no doubt that a server process cannot arbitrarily specify a value, and the kernel has a licensed scope. This range is implementation-related. It is difficult to have some kind of unification, generally this value will be less than 30. This is set to 1 to indicate that there is at most one pending connection 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, port number. As in the above example add Print statement output Clientsock and CLIENTADDR, you will find Clientsock for socket.socketobject,clientaddr= (' client IP ', port). The file class object is used in the following loop, and the server then displays some introductory information, reads a string from the client, displays an answer, and finally closes the client socket.