Python advanced [Article 1] socket and python advanced socket

Source: Internet
Author: User

Python advanced [Article 1] socket and python advanced 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 = 1024tcp_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 socketHOST = '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 @ node6 blog example] # python3 tclient. py >>> hello [Thu Sep 15 22:29:12 2016] B 'hello' >>> nihao [Thu Sep 15 22:29:32 2016] B' nihao'

Below are the server output

[Root @ node6 blog example] # python3 tserver. py waiting for connection... connected from: ('2017. 0.0.1 ', 127)
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 timeHOST = '127.0.0.1'PORT = 8009ADDR = (HOST,PORT)BUF_SIZE = 1024class 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 = 1024client = 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 @ node6 blog Example 2] # python3 tsocketclient. py >>>> helloThu Sep 15 23:53:31 2016 B 'hello' >>>> nihaoThu Sep 15 23:53:49 2016 B 'nihao' >>>> heheThu Sep 15 23:53:53 2016 B' he'

Below is the server output

[Root @ node6 blog Example 2] # python3 tsocketserver. py waiting for connection ...... connected from: ('2017. 0.0.1 ', 55385 )... connected from: ('2017. 0.0.1 ', 55385 )... connected from: ('2017. 0.0.1 ', 55385 )... connected from: ('2017. 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.