Python asynchronous socket programming
The Asynchronous Network can greatly improve the parallel processing capability of the program, so I wrote a topic to summarize the asynchronous communication in python.
1. synchronous communication between client and synchronous server 1.1. Example 1 in python socket communication instance. TCP server code
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_server.py
#
From socket import *
From time import ctime
HOST =''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
TcpSrvSock = socket (AF_INET, SOCK_STREAM)
TcpSrvSock. bind (ADDR)
TcpSrvSock. listen (5)
While True:
Print 'Waiting for connection ...'
TcpCliSock, addr = tcpSrvSock. accept ()
Print '... connected from:', addr
While True:
Data = tcpCliSock. recv (BUFSIZE)
If not data:
Break
TcpCliSock. send ('[% s] % s' % (ctime (), data ))
Print [ctime ()], ':', data
TcpCliSock. close ()
TcpSrvSock. close ()
2. TCP client code
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_client.py
From socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
TcpCliSock = socket (AF_INET, SOCK_STREAM)
TcpCliSock. connect (ADDR)
While True:
Data = raw_input ('> ')
If not data:
Break
TcpCliSock. send (data)
Data = tcpCliSock. recv (BUFSIZE)
If not data:
Break
Print data
TcpCliSock. close ()
2.2. Another example link to this example: http://blog.csdn.net/joeblackzqq/article/details/34860379
A server, a client, and a blocking method can only accept one client connection and communication at a time.
The client sends 'bye' to end the communication with the server. If 'shutdown 'is sent, the server will close itself!
1. server code:
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_server.py
#
From socket import *
From time import ctime
HOST =''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
TcpSerSock = socket (AF_INET, SOCK_STREAM)
TcpSerSock. bind (ADDR)
TcpSerSock. listen (5)
Quit = False
Shutdown = False
While True:
Print ('Waiting for connection ...')
TcpCliSock, addr = tcpSerSock. accept ()
Print ('... connected from:', addr)
While True:
Data = tcpCliSock. recv (BUFSIZE)
Data = data. decode ('utf8 ')
If not data:
Break
Ss = '[% s] % s' % (ctime (), data)
TcpCliSock. send (ss. encode ('utf8 '))
Print (ss)
If data = 'bye ':
Quit = True
Break
Elif data = 'shutdown ':
Shutdown = True
Break
Print ('Bye-Bye: [% s: % d] '% (addr [0], addr [1])
TcpCliSock. close ()
If shutdown:
Break
TcpSerSock. close ()
Print ('server has been ')
2. client code
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_client.py
#
From socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
TcpCliSock = socket (AF_INET, SOCK_STREAM)
TcpCliSock. connect (ADDR)
While True:
Data = input ('> ')
If not data:
Continue
Print ('input data: [% s] '% data)
TcpCliSock. send (data. encode ('utf8 '))
Rdata = tcpCliSock. recv (BUFSIZE)
If not rdata:
Break
Print (rdata. decode ('utf8 '))
If data = 'bye' or data = 'shutdown ':
Break
TcpCliSock. close ()
2. synchronous communication between client and Asynchronous server 1. server code
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: async_socket_server.py
#
Import socket
Import threading
Import SocketServer
Class ThreadedTCPRequestHandler (SocketServer. BaseRequestHandler ):
Def handle (self ):
Data = self. request. recv (1024)
Cur_thread = threading. current_thread ()
Response = "{}:{}". format (cur_thread.name, data)
Self. request. sendall (response)
Class ThreadedTCPServer (SocketServer. ThreadingMixIn, SocketServer. TCPServer ):
Pass
If _ name _ = "_ main __":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
Server = ThreadedTCPServer (HOST, PORT), ThreadedTCPRequestHandler)
Ip, port = server. server_address
# Start a thread with the server -- that thread will then start one
# More thread for each request
Server_thread = threading. Thread (target = server. serve_forever)
# Exit the server thread when the main thread terminates
Server_thread.daemon = True
Server_thread.start ()
Print "Server loop running in thread:", server_thread.name
Server. serve_forever ()
# Server. shutdown ()
2. client code
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_client.py
#
Import socket
Import threading
Import SocketServer
Def client (ip, port, message ):
Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Sock. connect (ip, port ))
Try:
Sock. sendall (message)
Response = sock. recv (1024)
Print "Received :{}". format (response)
Finally:
Sock. close ()
If _ name _ = "_ main __":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
Client (ip, port, "Hello World 1 ")
Client (ip, port, "Hello World 2 ")
Client (ip, port, "Hello World 3 ")
3. multi-threaded client code
To improve the degree of parallelism, you can use multiple threads to call
#! /Usr/bin/env python
#
#-*-Coding: UTF-8 -*-
# File: sync_socket_client.py
#
Import socket
Import threading
Import SocketServer
Def client (ip, port, message ):
Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Sock. connect (ip, port ))
Try:
Sock. sendall (message)
Response = sock. recv (1024)
Print "Received :{}". format (response)
Finally:
Sock. close ()
If _ name _ = "_ main __":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
Th1 = threading. Thread (target = client, args = (ip, port, "Hello World 1 ",))
YY = threading. Thread (target = client, args = (ip, port, "Hello World 2 ",))
Th3 = threading. Thread (target = client, args = (ip, port, "Hello World 3 ",))
Th1.start ()
Th2.start ()
Th3.start ()
Th1.join ()
Th2.join ()
Th3.join ()
4. Output example
Received: Thread-2: Hello World 1
Received: Thread-3: Hello World 2
Received: Thread-4: Hello World 3