A simple multi-thread TCP server tutorial using Python
This article mainly introduces how to use Python to implement a simple multi-thread TCP server. The running environment of the example is a Windows operating system. For more information, see
I recently read "python core programming". The book implements a simple one-to-one TCPserver, but in actual use, the one-to-one situation is obviously not good, so I studied how to start different threads (processes) on the server side to implement each link to a thread.
In fact, python has considered this requirement in the class design. We only need to inherit SocketServer. BaseRequestHandler from our own server.
The server code is as follows:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
#! /Usr/bin/env python
Import SocketServer
From time import ctime
HOST =''
PORT = 21567
ADDR = (HOST, PORT)
Class MyRequestHandler (SocketServer. BaseRequestHandler ):
Def handle (self ):
Print '... connected from:', self. client_address
While True:
Self. request. sendall ('[% s] % s' % (ctime (), self. request. recv (1024 )))
TcpServ = SocketServer. ThreadingTCPServer (ADDR, MyRequestHandler)
Print 'Waiting for connection ...'
TcpServ. serve_forever ()
|
The client code is as follows (basically the same as in the book, but the closed link in the loop is commented out ):
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
#! /Usr/bin/env python
From socket import *
HOST = 'localhost'
PORT = 21567
Bufsiz= 1024
ADDR = (HOST, PORT)
While True:
TcpCliSock = socket (AF_INET, SOCK_STREAM)
TcpCliSock. connect (ADDR)
Data = raw_input ('> ')
If not data:
Break
TcpCliSock. send ('% s \ r \ n' % data)
Data = tcpCliSock. recv (BUFSIZ)
If not data:
Break
Print data. strip ()
# TcpCliSock. close ()
|
From the client code, we can see that a new request is created every time a request is entered.
Test. After the server and client are started, enter the test in the client: