How to Implement TCP server and client in python
This example describes how to implement the TCP server and client in python. Share it with you for your reference. The details are as follows:
TCP server program (tsTserv. py ):
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
From socket import * From time import ctime HOST ='' PORT = 21567 Bufsiz= 1024 ADDR = (HOST, PORT) TcpSerSock = socket (AF_INET, SOCK_STREAM) TcpSerSock. bind (ADDR) TcpSerSock. listen (5) While True: Print 'Waiting for connection ...' TcpCliSock, addr = tcpSerSock. accept () Print '... connected from:', addr While True: Data = tcpCliSock. recv (BUFSIZ) If not data: Break TcpCliSock. send ('[% s] % s' % (ctime (), data )) TcpCliSock. close () TcpSerSock. close () |
TCP client program (tsTclnt. py ):
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
From socket import * HOST = 'localhost' PORT = 21567 Bufsiz= 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) Data1 = tcpCliSock. recv (BUFSIZ) If not data1: Break Print data1 TcpCliSock. close () |
Run Description: first run the server program, which is similar to opening the server to keep waiting for the customer's request, and then run the client program.
The running interface is as follows:
Server:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
D: \ code \ ex> python tsTserv. py Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... ... Connected from: ('192. 0.0.1 ', 127) Waiting for connection... |
Client:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 |
D: \ code \ ex> python tsTclnt. py > 1 [Thu Feb 02 15:52:21, 2012] 1 > 2 [Thu Feb 02 15:52:22, 2012] 2 > 3 [Thu Feb 02 15:52:22, 2012] 3 > 5 [Thu Feb 02 15:52:23, 2012] 5 > 6 [Thu Feb 02 15:52:24 2012] 6 > D: \ code \ ex> |
I hope this article will help you with Python programming.