Dave Python exercises 18-Network Programming

Source: Internet
Author: User

# Encoding = UTF-8 </P> <p >### ***************** network programming ********* * ****** </P> <p> # ************ Part 1: socket: communication endpoint ****************** </P> <p >## 1.1 socket <br/> # socket originated from in 1970s, the University of California Berkeley version of UNIX, this is what we call bsd unix. <Br/> # therefore, sockets are sometimes called "Berkeley sockets" or "BSD sockets ". Initially, sockets were designed for communication between multiple applications on the same <br/> # host. This is also called inter-process communication or IPC. There are two types of sockets: file-based <br/> # and network-based. </P> <p> # UNIX socket is the first socket family to be introduced. Its "Family Name" is af_unix (in posix1.g Standard <br/> # also called af_local), indicating "address family: Unix ". Most popular platforms, including python, use the term "address <br/> # family" and Its abbreviation "af ". In older systems, the address family is called "Domain" or "protocol family" and uses the abbreviation "pf" <br/> # Instead of "af ". Similarly, af_local (listed as standard in 2000-2001) will replace af_unix. However, for backward <br/> # compatibility, the two are equivalent in many systems. Python still uses af_unix. </P> <p> # Another socket is based on the network. It has its own family name: af_inet, or "address family: Internet ". <Br/> # Another address family af_inet6 is used for Internet Protocol version 6th (IPv6) addressing. There are also some other address families. Among all address families, af_inet is the most widely used one. <Br/> # added support for a Linux socket in Python 2.5: the af_netlink socket family allows the IPC between user code and kernel code to use a standard BSD set <br/> # concatenation interface. In addition, this method is more elegant and safer than the previous heavy solutions that add new system calls to the operating system, such as proc file system support or "IOCTL. <Br/>#< br/> # Python only supports af_unix, af_netlink, and af_inet families. </P> <p> #1.2 socket address: Host and port <br/> # If you compare a socket to a telephone plug-in, that is, the underlying structure of communication, the host and port are like a combination of area code and phone number <br/>. It's not enough hardware to make a call. You need to know who you want to call and where you want to call. An Internet address consists of the host and port necessary for Network <br/> # network communication. Needless to say, the other end must be listened. Otherwise, you will hear <br/> # the familiar voice "sorry, you are dialing an empty number. Please check it and play it again ". You may have seen a similar situation when surfing the Internet. <br/> # For example, "You cannot connect to this server. The server is unresponsive or inaccessible ". </P> <p> # valid port numbers range from 0 to 65535. The port number smaller than 1024 is reserved by the system. If the <br/> # you are using is a UNIX operating system, the reserved port number (and the corresponding service/protocol and socket type) you can use the/etc/services <br/> # file. </P> <p> #1.3 connection-oriented and connectionless <br/> #1.3.1 connection-oriented <br/> # No matter which address family you use. There are only two types of sockets. One is a connection-oriented socket, that is, before communication <br/> #, you must establish a connection, just as when you call a friend. This communication method is also known as "virtual circuit" or "stream concatenation <br/> ". Connection-oriented communication provides ordered, reliable, and non-repeated data transmission, and data edge is not added <br/>. This also means that each piece of information to be sent may be split into multiple copies, and each copy will arrive at the destination in a few places. <br/>. Then it is assembled in order and passed to the waiting application. <Br/> # The main protocol used to implement this connection is the Transmission Control Protocol (TCP ). To create a TCP socket, you must <br/> # specify the socket type as sock_stream. The TCP socket uses the sock_stream name to express its <br/> # feature as a stream socket. Because these sockets use the Internet Protocol (IP) to find hosts in the network, the entire system is generally referred to by <br/> # these two protocols (TCP/IP and IP, that is, TCP/IP. </P> <p >## 1.3.2 connectionless <br/> # the opposite of a virtual circuit is a datagram connectionless socket. This means that communication can be performed without establishing a connection. <Br/> # However, the data arrival sequence, reliability, and data repeatability cannot be ensured. The datagram retains the data boundary, which is shown in <br/> #. The data is not split into small pieces as the connection-oriented protocol. <Br/> # use a datagram to transmit data just like a postal service. Emails and packages may not necessarily arrive in the order they are sent. Fact <br/> # they may not be available at all! In addition, due to the complexity of the network, data may be transmitted repeatedly. <Br/> # since there are so many disadvantages of a datagram, why should we use it? Because <br/> # connection-oriented sockets must provide some guarantees and maintain virtual circuit connections, This is a heavy extra burden. The datagram does not have this <br/> # burden, so it is cheaper ". Generally, it provides better performance and is more suitable for some application scenarios. </P> <p> # The main protocol for implementing this connection is the User Datagram Protocol (UDP ). To create a UDP socket, you must <br/> # specify the socket type as sock_dgram. The name sock_dgram may have been guessed, from the word "datasync" <br/> # ("datagram "). Because these sockets use the Internet Protocol to find hosts in the network, the entire system formed in this way will be mentioned by the two protocols (UDP and IP, that is, UDP/IP. </P> <p> # *********** Part 2: network Programming in Python ******************* <br/> #2.1 socket () module functions <br/> # use socket. socket () function to create a socket. The syntax is as follows: <br/> # socket (socket_family, socket_type, protocol = 0) <br/> # socket_family can be af_unix or af_inet. Socket_type can be sock_stream or sock_dgram. <Br/> # For the meanings of these constants, refer to the previous explanations. The default value is 0. </P> <p> # create a TCP/IP socket. You need to call the socket in this way. socket (): <br/> # tcpsock = socket. socket (socket. af_inet, socket. sock_stream) <br/> # Similarly, create a UDP/IP socket. You need to do this: <br/> # udpsock = socket. socket (socket. af_inet, socket. sock_dgram) <br/>#< br/> # because the socket module has too many attributes. Here, the 'from module import * 'statement is used as an exception. Using <br/> # 'from socket import * ', we will bring all the attributes in the socket module to our namespace, in this way, <br/> # greatly reduce our code. <Br/> # tcpsock = socket (af_inet, sock_stream) <br/> # After we create a socket object, all interactions are performed by calling the method of the socket object. </P> <p >## 2.2 socket object (built-in) method </P> <p> # common functions of socket objects <br/> # function description <br/> #### server socket functions <br/> # S. BIND () bind the address (host, port number pair) to the socket <br/> # S. listen () starts TCP listening <br/> # S. accept () passively accepts tcp client connections (blocking) waiting for the connection to arrive <br/>#< br/>#### client socket function <br/> # S. connect () Actively initializes the TCP server connection <br/> # S. extended version of the connect_ex () connect () function. An error code is returned when an error occurs, instead of throwing an exception <br/> # <br/> ##### common socket functions <br/> # S. recv () receives TCP Data <br/> # S. send () sends TCP Data <br/> # S. sendall () completely sends TCP Data <br/> # s. Recvfrom () receives UDP data <br/> # S. sendto () sends UDP data <br/> # S. getpeername () is the remote address connected to the current socket. <br/> # S. getsockname () Current socket address <br/> # S. getsockopt () returns the parameter of the specified socket <br/> # S. setsockopt () sets the parameter of the specified socket <br/> # S. close () Close socket </P> <p >#### blocking-oriented socket methods <br/> # S. setblocking () sets the blocking and non-blocking modes of the socket. <br/> # S. setTimeout () sets the timeout value for blocking socket operations <br/> # S. gettimeout () gets the timeout value for blocking socket operations <br/> # <br/>#### file-oriented socket functions <br/> # S. fileno () socket File descriptor of the word <br/> # S. makefile () creates a file associated with the socket </P> <p> #2.3 creates a TCP server </P> <p> # pseudocode: <br/> # Ss = socket () # create a server socket <br/> # ss. BIND () # bind the address to the socket <br/> # ss. listen () # listener connection <br/> # inf_loop: # server infinite loop <br/> # cs = ss. accept () # accept the customer's connection <br/> # comm_loop: # communication loop <br/> # CS. recv ()/CS. send () # Dialog (receive and send) <br/> # CS. close () # Close customer socket <br/> # ss. close () # disable server socket (optional) </P> <p> # All sockets use socket. socket () function. The server needs to "Sit on a port" and wait for the request. <Br/> # it must be "Bound" to a local address. As TCP is a connection-oriented communication system, you must complete some settings before the TCP server <br/> # can start to work. The TCP server must "listen" (incoming) connections. After the settings are complete, <br/> # the server can enter an infinite loop. <Br/>#< br/> # A simple (single-threaded) server calls the accept () function to wait for the connection to arrive. By default, the accept () <br/> # function is blocked, that is, the program will be suspended before the connection arrives. Socket also supports non-blocking mode. <Br/> # Once a connection is received, the accept () function returns a separate client socket for subsequent communication. </P> <p> # after the temporary socket is created, the communication starts. Both the customer and the server use this new socket for <br/> # sending and receiving data until the communication party closes the connection or sends an empty string, the communication is over. </P> <p> # in the Code, when the customer's connection is closed, the server continues to wait for the connection from the next customer. The last line of the Code closes the socket of server <br/> # server. This step is optional because the server is in an infinite loop and cannot be taken. <Br/> # The main purpose of writing this sentence is to remind readers that when designing a more intelligent exit solution, for example, server <br/> # When the server is notified to be closed, make sure that the close () function is called. </P> <p> # example: tstserv. PY creates a TCP server program, after the client is connected, return 'Hello Dave '</P> <p> # encoding = UTF-8 </P> <p> # From socket import * <br/> # From time import ctime <br/> # host = ''# The host variable is empty, the BIND () function can be bound to all valid addresses. <Br/> # Port = 21567 <br/> # bufsiz = 1024 # Set the buffer size to 1 k <br/> # ADDR = (host, Port) <br/> # tcpsersock = socket (af_inet, sock_stream) <br/> # tcpsersock. BIND (ADDR) <br/> # tcpsersock. listen (5) # The maximum number of connections allowed to be connected at the same time. Later connections will be rejected. <Br/>#< br/> # While true: <br/> # print ('Waiting for connection... ') <br/> # tcpclisock, ADDR = tcpsersock. accept () <br/> # print ('... connected from: ', ADDR) <br/> # While true: <br/> # DATA = tcpclisock. recv (bufsiz) <br/> # if not data: <br/> # Break <br/> # tcpclisock. send (B 'hello Dave ') # note that only the bytes type can be sent in Python 3.x <br/>#< br/> # tcpclisock. close () <br/> # tcpsersock. close () </P> <p >## 2.4 create a tcp client User </P> <p> # pseudocode: <br/> # cs = socket () # Create Customer socket <br/> # CS. connect () # Try to connect to the server <br/> # comm_loop: # communication loop <br/> # CS. send ()/CS. recv () # Send/receive a dialog <br/> # CS. close () # Close customer socket </P> <p> # All sockets are composed of socket. create a socket () function. After the customer has a socket, he can immediately <br/> # Call the connect () function to connect to the server. After the connection is established, you can start a conversation with the server. After the conversation ends, the customer can close the socket and end the connection. </P> <p> # tctlnt. py code. The program connects to the server and sends 'Hello world' to the server ', the server returns 'Hello Dave '<br/> # From socket import * <br/> # host = 'localhost' # server host name and port number <br/> # Port = 21567 # the port number must be exactly the same as that set on the server <br/> # bufsiz = 1024 <br/> # ADDR = (host, port) <br/> # tcpclisock = socket (af_inet, sock_stream) <br/> # tcpclisock. connect (ADDR) <br/> # While true: <br/> # tcpclisock. send (B 'hello World') <br/> # DATA = tcpclisock. recv (bufsiz) <br/> # <br/> # If not data: <br/> # Break <br/> # print (data) <br/> # tcpclisock. close () </P> <p >## 2.6 create a UDP server <br/> # because the UDP server is not connection-oriented, therefore, you do not need to perform so many settings as the TCP server does. In fact, you don't need to set anything, just wait for the incoming connection. <Br/> # Ss = socket () # create a server socket <br/> # ss. BIND () # bind a server socket <br/> # inf_loop: # infinite server loop <br/> # cs = ss. recvfrom ()/SS. sendto () # conversation (receiving and sending) <br/> # ss. close () # Close the server socket <br/> # As shown in the pseudocode, the method used is to first create a socket and then bind it to a local address (host/Port Pair. <Br/> # an infinite loop contains three steps: receiving a message from the customer, returning the result with a timestamp, and returning the Next message. <Br/> # Similarly, the close () function is optional because the Code does not jump out of an infinite loop. The reason for writing this sentence is <br/> # remind the reader that when designing a more intelligent exit solution, make sure that the close () function will be called. </P> <p >## UDP timestamp server (tsuserv. PY) </P> <p> # From socket import * <br/> # From time import ctime <br/> # host = ''<br/> # port = 21567 <br/> # bufsiz = 1024 <br/> # ADDR = (host, port) <br/> # udpsersock = socket (af_inet, sock_dgram) <br/> # udpsersock. BIND (ADDR) <br/> # While true: <br/> # print ('Waiting for message... ') <br/> # data, ADDR = udpsersock. recvfrom (bufsiz) <br/> # udpsersock. sendto (ctim E (). encode ('utf-8'), ADDR) # note that sendto needs to be transmitted using bytes in Python 3, so encode must be used for conversion <br/> # print ('... stored ed from and returned to: ', ADDR) <br/> # udpsersock. close () </P> <p >## 2.7 create a UDP client <br/> # pseudocode: <br/> # cs = socket () # create a customer socket <br/> # comm_loop: # communication loop <br/> # CS. sendto ()/CS. recvfrom () # Send/receive a dialog <br/> # CS. close () # Close customer socket </P> <p> # UDP client, the program will prompt the user to enter the information to be sent to the server, and display the result of Timestamp added to the server. </P> <p> # From socket import * <br/> # host = 'localhost' <br/> # Port = 21567 <br/> # bufsiz = 1024 <br/> # ADDR = (host, port) <br/> # udpclisock = socket (af_inet, sock_dgram) <br/> # While true: <br/> # DATA = input ('>') <br/> # if not data: <br/> # Break <br/> # udpclisock. sendto (data. encode ('utf-8'), ADDR) # note that sendto needs to be transmitted using bytes in Python 3, so encode must be used for conversion <br/> # data, ADDR = udpclisock. Recvfrom (bufsiz) <br/> # if not data: <br/> # Break <br/> # print (data) <br/> # udpclisock. close () </P> <p> # Run the server first. When running the client, the system prompts you to enter data, and then the server returns the time. </P> <p >## 2.8 socket module attributes </P> <p> # socket module attributes <br/> # Attribute Name Description <br/ >#< br/>#### data attributes <br/> # af_unix, af_inet, af_inet6 socket family supported by python <br/> # so_stream, so_dgram socket type (TCP = stream, UDP = datagram) <br/> # has_ipv6 indicates whether IPv6 flag variables are supported <br/> # <br/>#### exception <br/> # error socket errors <br/> # herrora host and address-related errors <br/> # gaierror address-related errors <br/> # timeout <br/> # <br/>#### function <br/> # socket () create a socket object with the specified address family, socket type, and protocol type (optional) <br/> # socketp Air () creates a socket object with the specified address family, socket type, and protocol type (optional) <br/> # fromfd () use an opened file descriptor to create a socket object <br/> # <br/>#### data attributes <br/> # SSL () initialize a Secure Socket Layer (SSL) on the socket ). No certificate verification is performed. <Br/> # getaddrinfo () obtain the address information <br/> # getfqdn () returns the complete domain name <br/> # gethostname () obtain the extended version of the current host name <br/> # gethostbyname () obtained from the host name <br/> # gethostbyname_ex () gethostbyname (). The host name is returned, list of all aliases and IP addresses of the host. <Br/> # gethostbyaddr () obtains DNS information from the IP address, and returns a triple similar to gethostbyname_ex. <Br/> # getprotobyname () gets the corresponding number by the protocol name (such as 'tcp. <Br/> # getservbyname ()/gets the corresponding port number from the service name or opposite <br/> # In the getservbyport () function, the protocol name is optional. <Br/> # ntohl ()/ntohs () converts an integer from the network byte sequence to the host byte sequence <br/> # htonl ()/htons () convert an integer from host byte to network byte <br/> # inet_aton ()/to a 32-bit integer and a reverse function. (Valid only for IPv4 addresses) <br/> # inet_ntoa () <br/> # inet_ton ()/converts an IP address into a binary format and a reverse function. (Valid only for IPv4 addresses) <br/> # inet_ntop () <br/> # getdefatimetimeout ()/get/set the default socket timeout time, in seconds (floating point number) <br/> # setdefatimetimeout () <br/>

Bytes -------------------------------------------------------------------------------------------------------
Blog: http://blog.csdn.net/tianlesoftware
WEAVER: http://weibo.com/tianlesoftware
Email: dvd.dba@gmail.com
Dba1 group: 62697716 (full); dba2 group: 62697977 (full) dba3 group: 62697850 (full)
Super DBA group: 63306533 (full); dba4 group: 83829929 (full) dba5 group: 142216823 (full)
Dba6 group: 158654907 (full) dba7 group: 69087192 (full) dba8 group: 172855474
DBA super group 2: 151508914 dba9 group: 102954821 chat group: 40132017 (full)
-- Add the group to describe the relationship between Oracle tablespace and data files in the remarks section. Otherwise, the application is rejected.

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.