Python's Path to Growth "Nineth": Network programming

Source: Internet
Author: User

One, socket

1.1. Socket socket
Sockets are originally created for applications on the same host, allowing a program (aka one process) running on the host to communicate with another running program. This is known as interprocess communication (Inter process COMMUNICATION,IPC). There are two types of sockets: file-based and network-oriented.

The first type: file-based
Because two processes are running on the same computer, these sockets are file-based, which means that the file system supports their underlying infrastructure. This can be said, because the file system is a shared constant between multiple processes running on the same host.
The second type: network-based
Network-based sockets, with their own family name Af_inet, or address family: Internet

Address family (addr family, abbreviation AF)

1.2. Connection-oriented and non-connected sockets
Connection-oriented communication provides serialized, reliable, and non-repeatable data delivery without logging boundaries. This basically means that each message can be split into multiple fragments, and each message fragment ensures that it reaches the destination, then combines them sequentially, and finally passes the full message to the waiting application.
The primary protocol for implementing this type of connection is Transmission Control Protocol (TCP). In order to create a TCP socket, you must use SOCK_STREAM as the socket type.


The primary protocol that implements no connection is User Datagram Protocol (UDP). In order to create a UDP socket, you must use SOCK_DGRAM as the socket type.

Second, the network programming in Python

2.1. Socket () module function
To create a socket, you must use the Socket.socket () function, which generally has the following syntax.
Sockets (Socket_family, Socket_type, protocol=0)
Therefore, in order to create a TCP/IP socket, you can call Socket.socket () in the following way.
Tcpsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Similarly, in order to create a UDP/IP socket, the following statement needs to be executed.
Udpsock = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)

Parameter one: Address cluster socket_family
Socket.af_inet #IPv4 (default)
Socket.af_inet6 #IPv6
Socket.af_unix #只能够用于单一的unix系统进程间通信
Parameter two: type Socket_type
Socket. Sock_stream #流式socket, for TCP (default)
Socket. Sock_dgram #数据报式socket, for UDP
Socket. Sock_raw #原始套接字, ordinary sockets can not handle the ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_ The HDRINCL socket option constructs an IP header by the user.
Socket. SOCK_RDM #是一种可靠的UDP形式, which ensures that interactive datagrams are not guaranteed in order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.
Socket. Sock_seqpacket #可靠的连续数据包服务
Parameter three: protocol
Protocol is usually omitted, the default is 0, the system will automatically select an appropriate protocol based on the address format and the socket category.


Because there are many socket module properties, if you use "from socket import *", they introduce the socket attribute into the namespace. While it may seem troublesome, the code will be greatly shortened in this way.
Tcpsock = socket (af_inet, SOCK_STREAM)
Once a socket object is available, the method of using the socket object will allow for further interaction.

2.2. Socket object (built-in) method
Common socket object methods and properties

2.3. General pseudo-code to create generic TCP server
Pseudo-code: Server
SS = socket () #创建服务器套接字
Ss.bind () #套接字与地址绑定
Ss.listen () #监听连接
Inf_loop: #服务器无限循环
cs = ss.accept () #接收客户端连接, resulting in blocking
Comm_loop: #通信循环
CS.RECV ()/cs.send () #对话 (Receive/Send)
Cs.close () #关闭客户端套接字
Ss.close () #关闭服务器套接字 #可选

Pseudo code: Client
CS = socket () #创建客户端套接字
Cs.connect () #尝试连接服务器
Comm_loop: #通信循环
Cs.send ()/cs.recv () #对话 (send/Receive)
Cs.close ()

 fromSocketImport* fromTimeImportCtimehost="'PORT= 9999Bufsiz= 1024ADDR=(HOST, PORT) Tcpsersock=socket (af_inet, Sock_stream) tcpsersock.bind (ADDR) Tcpsersock.listen (5) whileTrue:Print('waiting for connection ...') Tcpclisock, addr=tcpsersock.accept ()Print('... connected from:', addr) whileTrue:data=tcpclisock.recv (Bufsiz)if  notData: Breaktcpclisock.send (bytes (CTime (), Encoding="Utf-8") +data) Tcpclisock.close () tcpsersock.close ()
Explanation: The 1th block of code: all the properties of the Time.ctime () and socket modules are imported. The 2nd code block: The host variable is blank, which is the identity of the bind () method, indicating that it can use any available address. We also chose a random port number. Set the buffer size to 1KB. This capacity can be changed based on network performance and process needs. The parameter of the Listen () method is the maximum number of incoming connection requests before the connection is forwarded or rejected. The 3rd block of code: the TCP server socket (Tcpsersock) is assigned, followed by a call to bind the socket to the server address and to turn on the TCP listener. Code block 4th: Once you enter the infinite loop of the server, we wait (passively) for the client to connect. When a connection request appears, we enter the conversation loop where we wait for the message sent by the client. If the message is blank, this means that the client has exited, so at this point we will jump out of the conversation loop, close the current client connection, and wait for another client to connect. If you do get a message sent by the client, it is formatted and returns the same data, but the current timestamp prefix is added to the data. The last line is never executed, it's just a reminder to the reader that if you write a handler to consider a more graceful exit, you should call the close () method.
 fromSocketImport*HOST='127.0.0.1'  #or ' localhost 'PORT = 9999Bufsiz= 1024ADDR=(HOST, PORT) Tcpclisock=socket (af_inet, Sock_stream) tcpclisock.connect (ADDR) whileTrue:data= Input ('>>:')    if  notData: Breaktcpclisock.send (bytes (data,'Utf-8')) Data=tcpclisock.recv (Bufsiz)if  notData: Break    Print(Str (data, encoding="Utf-8"))#same as the following statement    #Print (Data.decode (' Utf-8 '))Tcpclisock.close ()
Explanation: code block 1th: Import all attributes from the Socket module 2nd block of code: the host and port variables refer to the server's hostname and name. Because the test is run on the same computer, host contains the local host name. Port number port should be exactly the same as the one you set for the server. Also, set the buffer size to 1KB. The 3rd block of code: The TCP client socket is assigned, which is then actively invoked and connected to the server. The 4th block of code: The client also has an infinite loop, but that doesn't mean it will run forever like a server loop. The client loop will jump out in the following two conditions: The user does not have input, or the server terminates and the call to the Recv () method fails. Otherwise, under normal circumstances, the user enters some string data and sends the data to the server for processing. The client then receives a timestamp-added string and displays it on the screen.
Execute the above code output result: >>:itue Sep 19:11:20 2016i

Python's Path to Growth "Nineth": Network programming

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.