Socket for python learning

Source: Internet
Author: User
The original meaning of Socket is "hole" or "Socket ". As a BSDUNIX process communication mechanism, it is also called & quot; socket & quot;. it is used to describe IP addresses and ports and is a communication chain handle, the original meaning of Socket is "hole" or "Socket ". As a process communication mechanism of bsd unix, it is also called "socket". it is used to describe IP addresses and ports. it is a communication chain handle and can be used to implement communication between different virtual machines or computers.

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

Establishing a network communication connection requires at least one port number (socket ). Socket is essentially a programming interface (API). It encapsulates TCP/IP. TCP/IP also provides interfaces that can be used by programmers for Network Development. this is the Socket programming interface; HTTP is a car that encapsulates or displays data in a specific form. Socket is an engine that provides network communication capabilities.

Next, let's talk about the python socket.

1. socket module

Use the socket. socket () function to create a socket. The syntax is as follows:

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

Socket_family can be the following parameter:

Socket. AF_INET IPv4 (default)

Socket. AF_INET6 IPv6

Socket. AF_UNIX can only be used for inter-process communication in a Single Unix system

Socket_type can be the following parameter:

Socket. SOCK_STREAM streaming socket, for TCP (default)

Socket. SOCK_DGRAM datagram socket, for UDP

Socket. the original socket of SOCK_RAW. a common socket cannot process network packets such as ICMP and IGMP, while SOCK_RAW can. Secondly, SOCK_RAW can also process special IPv4 packets. In addition, the original socket, you can use the IP_HDRINCL socket option to construct an IP address header.

Socket. SOCK_RDM is a reliable UDP format, that is, ensure the delivery of datagram but not the order. SOCK_RAM is used to provide low-level access to the original protocol. it is used when special operations are required, such as sending ICMP packets. SOCK_RAM is generally only used by programs run by senior users or administrators.

Socket. SOCK_SEQPACKET reliable continuous packet service

Protocol parameters:

0 (default) is a protocol related to a specific address family. if it is 0, the system automatically selects a suitable protocol based on the address format and set type.

2. socket object built-in method

Server Socket functions

S. bind (): bind the address (IP address, port) to the socket. the parameter must be in the format of a tuple, for example, s. bind ('192. 0.0.1 ', 127 ))

S. listen (5) starts listening, and 5 is the maximum number of suspended connections.

S. accept () passively accepts client connection, blocking, waiting for connection

Client Socket functions

S. connect () connects to the server. the parameter must be in the format of a tuple, for example, s. connect ('2017, 0.0.1 ', 127 ))

Common Socket functions

S. recv (1024) receives TCP data, and 1024 is the size of one data receipt.

S. send (bytes) sends TCP data. the format of data sent by python3 must be bytes.

S. sendall () completely sends data, and internally calls send cyclically

S. close () close socket

Example 1. simple socket program

Server

#!/usr/bin/env python# _*_ coding:utf-8 _*_import socketimport timeIP_PORT = ('127.0.0.1',8009)BUF_SIZE = 1024 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 is explained:

1 ~ 4 rows

The first line is the Unix startup information line, and then the time and socket modules are imported.

5 ~ 10 rows

IP_PORT declares the IP address and port for the global variable, indicating that the bind () function is bound to this address, and the buffer size is set to 1 K, listen () the function indicates the maximum number of connections allowed at the same time, and will be denied later.

11 ~ To the last line

Wait until the connection arrives. When there is a connection, enter the dialog loop and wait for the client to send data. If the message is blank, it indicates that the client has exited, and the next connection will arrive after the loop exists. After obtaining the client message, add a timestamp before the message and return it. The last line will not be executed, because the loop will not exit, so the server will not execute close (). Just remind you not to forget to call the close () function.

Client

#!/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 rows

The HOST and PORT variables indicate the IP address and PORT number of the server. Because the demonstration is on the same server, the IP addresses are all 127.0.0.1. if the demonstration is run on another server, modify it accordingly. The port number must be the same as that on the server. Otherwise, the communication will fail. The buffer size is still 1 K.

The client socket is created in 10 rows and then connected to the server

13 ~ 21 rows

The client also has an infinite loop. the client's loop exits after any of the following two conditions: 1. if the user input is empty or the server's response message is empty. Otherwise, the client will send the string you entered to the server for processing, and then receive the string with a timestamp returned by the server.

Run client and server programs

The following are the input and output of the client:

[root@pythontab]# python client.py >>> hello python[Thu Sep 15 22:29:12 2016] b'hello python'

Below are the server 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. A large amount of sample code is used to simplify the implementation of network clients and servers. The module has implemented some available classes.

Instance 1: Use socketserver to implement the same functions as the preceding socket () instance.

Server program code

#!/usr/bin/env python# _*_ coding:utf-8 _*_import socketserverimport time HOST = '127.0.0.1'PORT = 8009ADDR = (HOST,PORT)BUF_SIZE = 1024 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 rows

The main work is here. A subclass is generated from the BaseRequestHandler class of socketserver and the handle () function is rewritten.

When a message is sent from a client, the handle () function is called.

19 ~ 21 rows

The last part of the code adds the custom request processing class (Myserver) with the given IP address and port ). Then enter the infinite loop of waiting for client requests and processing client requests.

Client program code

import socketHOST = '127.0.0.1'PORT = 8009ADDR = (HOST,PORT)BUF_SIZE = 1024 client = socket.socket()client.connect(ADDR) 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()

Run the server and client code

Below is the client output

[root@pythontab]# python socketclient.py >>> hello pythonThu Sep 15 23:53:31 2016 b'hello python'>>> hello pythontabThu Sep 15 23:53:49 2016 b'hello pythontab'

Below is the server 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)

The above is a detailed description of the socket in python learning advanced. For more information, see other related articles in the first PHP community!

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.