Python Network programming: Socket

Source: Internet
Author: User

Before learning the socket, we should review the relevant network knowledge.

OSI Seven layer Model: Application layer, presentation layer, session layer, Transport layer, network layer, data link layer, physical layer. The OSI seven layer model is the basic structure of a network defined by ISO, which includes not only some concepts and structures, but also a series of protocols. TCP/IP layer four model: since there is the OSI seven layer model, why should we also define a TCP/IP four-layer model, that is because the OSI seven-layer model is too broad, many concepts can not be implemented, there is no need to implement, therefore, the actual production is widely used in the TCP/IP four layer structure, Their correspondence is shown in the following table:

Tcp / ip

Osi

Application Layer

Application Layer

Presentation Layer

Session Layer

Host-to-host layer (TCP) (also known as transport Layer)

Transport Layer

Network Layer (IP) (also known as interconnect layer)

Network layer

Network interface layer (also known as link layer)

Data Link Layer

Physical Layer

The socket to be introduced today is located between the application layer and the transport layer.   Example: And for TCP, to figure out the transmission of data streams, three handshakes and four waves are something that must be known. Python network programming has said so much, now get to the point, Python network programming is to use the socket to create applications and transfer direct links,Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)

The difference between a socket and file:

    • The file module is "open", "Read and write" "Close" for a specified document
    • The socket module is a typical C/s architecture for "open", "Read and write" "Off" for both server-side and client sockets. Here is the simple transfer mode of the socket:

To understand the socket communication program through a simple example:

#!/use/bin/env python#_*_ coding:utf_8 _*_ImportSocketip_port=('127.0.0.1', 9000) s=socket.socket ()#creating a Socket objectS.connect (Ip_port)#Establish a connectionS.send (Bytes ('hello!', encoding='Utf-8'))#send data, must be in byte formatSERV_DATA=S.RECV (1024)#receiving data from the server, recv (1024) defines how much you can receive each timePrint(Serv_data)#Print OutputS.close ()
Socket Client
#!/use/bin/env python#_*_ coding:utf_8 _*_Importsocketip_addr=('127.0.0.1', 9000) R=Socket.socket () r.bind (ip_addr) R.listen (5)#Maximum number of connections whileTrue:#Typically, each socket address (Protocol/network address/port) is allowed to be used only once. Place it in a loop and close every time the reply is completedConn,recv=r.accept ()#Conn represents the pipeline established by this connectionCLIENT_DATA=CONN.RECV (1024)#get the data sent by the client    Print(client_data) conn.send (bytes ('hello,client', encoding='Utf-8') ) Conn.close ()
Socket Server

For socket programming, you must write two py files, one server and one client. But there are two points to emphasize:

1. After Python3, the socket is passed the bytes type of data, the string needs to be converted first, String.encode () can be;

The bytes data received at the other end wants to be converted into a string, as long as Bytes.decode ().

2. During normal communication, the accept and recv methods are blocked, and the program pauses there until there is data coming.

Method analysis

SK = Socket.socket (socket.af_inet,socket. sock_stream,0) Instantiate an object of the socket class  

Parameter one: Address cluster

Socket.af_inet IPv4 (default)
Socket.af_inet6 IPV6

Socket.af_unix can only be used for single UNIX system interprocess communication

Parameter two: type

Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP

Socket. Sock_raw the original socket, the ordinary socket can not handle 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 is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the 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 Reliable Continuous Packet service

Parameter three: protocol

0 (default) protocol related to a particular address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.

Here is an example of a UDP protocol, noting that there is no concept of accept and connect.

#Service SideImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket (Socket.af_inet,socket. sock_dgram,0) Sk.bind (ip_port) whileTrue:data= SK.RECV (1024)    Print(data)#ClientImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket (Socket.af_inet,socket. sock_dgram,0) whileTRUE:INP= Input ('Data:'). Strip ()ifINP = ='Exit':         Breaksk.sendto (Inp,ip_port) sk.close ()
UDP Demo

 Sk.bind (Address)

S.bind binds the socket to the address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port).

Sk.listen (Backlog)

Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected, that is, in addition to the connection that is currently being communicated with the server.

The number of connections entering the link pool. Connections exceeding this number will be actively rejected by the server and cannot be established. The backlog equals 5, indicating that the kernel has received a connection request, but the server

The maximum number of connections that have not been called accept for processing is 5, and this value cannot be infinitely large because the connection queue is maintained in the kernel

Sk.setblocking (BOOL)

Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error. Socket becomes the key parameter of non-blocking mode by blocking!

Sk.accept ()

Accepts the connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.

Incoming TCP Client connection (blocked) waiting for connection

Sk.connect (Address)

The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.

SK.CONNECT_EX (Address)

Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061

Sk.close ()

Close socket

SK.RECV (Bufsize[,flag])

Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.

Sk.recvfrom (Bufsize[.flag])

Similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.

Sk.send (String[,flag])

Sends data from a string to a connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string. That is, the specified content may not be sent all.

Sk.sendall (String[,flag])

Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.

Internally, the send is called recursively, sending all the content.

Sk.sendto (string[,flag],address)

Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.

Sk.settimeout (Timeout)

Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, the timeout period should be set when the socket was first created,

Because they may be used for connected operations (such as client connections up to 5s waiting)

Sk.getpeername ()

Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).

Sk.getsockname ()

Returns the socket's own address. Typically a tuple (ipaddr,port)

Sk.fileno ()

File descriptor for sockets

Socketserver Module

The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. That is, when each client requests a connection to the server, the socket server creates a "thread" or "process" within the servers that is specifically responsible for all requests from the current client.

Threadingtcpserver (multi-threaded)

The Soket server implemented by Threadingtcpserver creates a " thread " For each client that is used to interact with the client. The server is the equivalent of a manager, after receiving the connection and creating a new thread, then forget it, the subsequent communication is the connection between the thread and the client, it is important to understand this!

1. Threadingtcpserver Foundation

Using Threadingtcpserver:

    • Create a class that inherits from Socketserver.baserequesthandler
    • A method called handle must be defined in a class
      • Start Threadingtcpserver
#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketserverclassMyServer (socketserver. Baserequesthandler):defhandle (self):#Print Self.request,self.client_address,self.serverconn =self.request Conn.sendall ('Welcome to call 10086, please input 1xxx,0 to manual service.') Flag=True whileFlag:data= CONN.RECV (1024) Data= str (data, encoding="Utf-8")            ifdata = ='Exit': Flag=Falseelifdata = ='0': Conn.sendall (bytes ('through may be recorded. Balabala a big push.', encoding="Utf-8"))            Else: Conn.sendall (bytes ('Please re-enter', encoding="Utf-8"))if __name__=='__main__': Server= Socketserver. Threadingtcpserver (('127.0.0.1', 8009), MyServer) Server.serve_forever ()
Threadingtcpserver
#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 8009) SK=Socket.socket () sk.connect (Ip_port) sk.settimeout (5) whileTrue:data= SK.RECV (1024)    Print('Receive:', data) INP= Input ('Please input:') Sk.sendall (bytes (INP, encoding="Utf-8"))    ifINP = ='Exit':         Breaksk.close ()
Socket Client

Analyze the server-side code, with these key points:

    • The connection object is no longer socket.socket () in the socket module, but self.request, which is fixed syntax, immutable! Subsequent calls to the Send and recv methods are all using Self.request
    • The handle method is the processing core of the entire connection, and once it runs, the entire connection is broken (but the other threads and other clients are OK), so an infinite loop is typically set here.
    • During the instantiation of server = Socketserver.threadingtcpserver (' 127.0.0.1 ', 8009, MyServer), you must pass in the class that you created as a parameter
    • Server.serve_forever () indicates that the server will run forever under normal conditions

The internal invocation process is:

    • Start the service-side program
    • Executes the tcpserver.__init__ method, creates the server-side socket object and binds the IP and port
    • Executes the baseserver.__init__ method to assign a custom inherited class Myrequesthandle from Socketserver.baserequesthandler to Self.requesthandlerclass
    • Executes the Baseserver.server_forever method, while the loop is always listening for client requests to arrive ...
    • When a client connection arrives at the server
    • Executes the Threadingmixin.process_request method, creating a "thread" to handle the request
    • Execute the Threadingmixin.process_request_thread method
    • Executes the Baseserver.finish_request method and executes self. Requesthandlerclass () is the construction method that executes the custom Myrequesthandler (automatically calls the constructor of the base class Baserequesthandler, which in turn calls the Handle method of Myrequesthandler)

Python Network programming: 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.