Python Advanced Socket Detailed

Source: Internet
Author: User
The English literal of the socket is "hole" or "socket". As a BSD Unix process communication mechanism, commonly referred to as a "socket", used to describe IP addresses and ports, is a handle to a communication chain that can be used to implement communication between different virtual machines or different computers.

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this connection is called a socket.

Establish a network communication connection with at least a pair of port numbers (sockets). Socket is the nature of the programming Interface (API), TCP/IP encapsulation, TCP/IP also to provide the interface for programmers to do network development, this is the socket programming interface; HTTP is a sedan that provides a specific form of encapsulation or display of data; The socket is the engine that provides the ability to communicate over the network.

Here's a python socket.

1.socket Module

You use the Socket.socket () function to create a socket. Its syntax is as follows:

Socket.socket (socket_family,socket_type,protocol=0)


Socket_family can be the following parameters:


Socket.af_inet IPv4 (default)

Socket.af_inet6 IPV6


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


Socket_type can be the following parameters:


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


Protocol parameters:


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.


2. Socket object built-in method


Server-side socket functions


S.bind () Bind address (IP address, port) to socket, parameter must be in tuple format such as: S.bind ((' 127.0.0.1 ', 8009))


S.listen (5) Start listening, 5 is the maximum number of pending connections


S.accept () passively accepts client connections, blocks, waits for connection


Client socket functions


S.connect () to the server side, the parameters must be in the tuple format for example: S.connect (' 127,0.0.1 ', 8009))


Socket functions for public use


S.RECV (1024) receives TCP data, 1024 is the size of the data received at one time


S.send (bytes) sends TCP data, Python3 send data must be in bytes format


S.sendall () Send data in full, internal loop calls send


S.close () Close socket


Example 1. Simple implementation of the socket program

Server Side

#!/usr/bin/env python# _*_ coding:utf-8 _*_import socketimport timeip_port = (' 127.0.0.1 ', 8009) buf_size = 1024x768  tcp_ Server = Socket.socket () tcp_server.bind (Ip_port) Tcp_server.listen (5) while  True:    print ("Waiting for Connection ... ")    conn,addr = tcp_server.accept ()    print (" ... connected from: ", addr) while    True:        data = TCP_SERVER.RECV (buf_size)        if not data:break        tcp_server.send (' [%s]%s '% (Time.ctime (), data))  Tcp_ Server.close ()

The above code explains:


1~4 Line


The first line is the Unix startup information line, which is then imported into the time module and the socket module


5~10 Line


Ip_port declares the IP address and port for the global variable, which means that the bind () function binds to this address, and the buffer size is set to the 1k,listen () function to indicate the maximum number of connections allowed to come in at the same time, and later rejected.


11~ to the last line


After entering the server loop, passively waits for the connection to arrive. When there is a connection, enter the conversation loop and wait for the client to send the data. If the message is empty, indicating that the client has exited, jump out of the loop and wait for the next connection to arrive. After the client message is received, a timestamp is added before the message and then returned. The last line is not executed because the loop does not exit, so the server does not execute close (). Just remind me not to forget to call the close () function.


Client Side

#!/usr/bin/env python

# _*_ Coding:utf-8 _*_import socket  HOST = ' 127.0.0.1 ' PORT = 8009buf_size = 1024ADDR = (host,port)  client = socket . Socket () Client.connect (ADDR) while  True:    data = input (">>>")    if not data:break    Client.send (bytes (data,encoding= ' utf-8 '))    recv_data = Client.recv (buf_size)    if not recv_data:break    Print (Recv_data.decode ())      Client.close ()

5~11 Line

The host and port variables represent the IP address and port number of the server. Because the demo is on the same server, the IP address is 127.0.0.1, and if it is running on a different server, make the appropriate modifications. The port number must be identical to the server side or it cannot communicate. The buffer size is still 1K.


Client sockets are created on line 10 and then go to connect to server side


13~21 Line


The client also loops indefinitely, and the client's loop exits after any one of the following two conditions: 1. The user input is empty or the server-side response message is empty. Otherwise, the client sends a user-entered string to the server for processing, and then receives a timestamp-stamped string returned by the display server.


Running client programs and server-side programs


The following is the client's input and output

[root@pythontab]# python client.py >>> Hello python[thu Sep 22:29:12] b ' Hello python '


The following is the service-side output

[root@pythontab]# python server.py waiting for connection......connected from: (' 127.0.0.1 ', 55378)

3.socketserver Module

Socketserver is a high-level module in the standard library. Used to simplify the extensive boilerplate code needed to implement network clients and servers. Some of the classes that can be used have been implemented in the module.


Example 1: Using Socketserver to implement the same functionality as the above socket () instance


Service-Side program code

#!/usr/bin/env python# _*_ coding:utf-8 _*_import socketserverimport time  HOST = ' 127.0.0.1 ' PORT = 8009ADDR = (host,po RT) Buf_size = 1024x768  class Myserver (Socketserver. Baserequesthandler):    def handle (self):        while True:            print ("... connected from:", self.client_address)            data = SELF.REQUEST.RECV (buf_size)            if not data:break            self.request.send (bytes ("%s%s"% (Time.ctime (), Data))  Server = Socketserver. Threadingtcpserver (addr,myserver) print ("Waiting for Connection ...") Server.serve_forever ()


11~17 Line


The main work is here. Derive a subclass from the Baserequesthandler class of Socketserver and override the handle () function.


The handle () function is called when a message is sent to the client.


19~21 Line


The last part of the code adds a custom processing request class (Myserver) with the given IP address and port. It then enters an infinite loop that waits for the client to request and process the client request.


Client program code

Import sockethost = ' 127.0.0.1 ' PORT = 8009ADDR = (host,port) buf_size = 1024x768  client = Socket.socket () client.connect (AD DR) while  True:    data = input (">>>")    if not data:continue    client.send (bytes (data,encoding= ' Utf-8 '))    recv_data = Client.recv (buf_size)    if not recv_data:break    print (Recv_data.decode ())  Client.close ()

Executing the server and client code


The following is the client output

[root@pythontab]# python socketclient.py >>> Hello pythonthu Sep 23:53:31 b ' Hello python ' >>> hel Lo pythontabthu Sep 23:53:49 b ' Hello Pythontab '


The following is the service-side output

[root@pythontab]# python socketserver.py waiting for connection......connected from: (' 127.0.0.1 ', 55385) ... connected From: (' 127.0.0.1 ', 55385) ... connected from: (' 127.0.0.1 ', 55385) ... connected from: (' 127.0.0.1 ', 55385)
  • 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.