This article illustrates the way Python implements TCP server-side and client. Share to everyone for your reference. Specifically 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 (A F_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:brea K 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_s Tream) Tcpclisock.connect (ADDR) while true:data = Raw_input (' > ') if not data:break (data) Tcpclisock.send = TCP CLISOCK.RECV (Bufsiz) if not data1:break print data1 tcpclisock.close () |
Run instructions: Run the server program first, the role is similar to open the server to keep waiting for customer requests, and then run the client program.
The running interface is as follows:
Server side:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13-14 |
D:codeex>python tstserv.py waiting for connection ... connected from: (' 127.0.0.1 ', 2883) waiting for connection .... .. Connected from: (' 127.0.0.1 ', 2885) waiting for connection ... connected from: (' 127.0.0.1 ', 2889) waiting for Connectio N ... connected from: (' 127.0.0.1 ', 2891) waiting for connection ... connected from: (' 127.0.0.1 ', 2892) waiting for C Onnection ... connected from: (' 127.0.0.1 ', 2893) waiting for connection ... |
Client:
?
| 1 2 3 4 5 6 7 8 9 10 11 12-13 |
D:codeex>python tstclnt.py > 1 [Thu Feb 15:52:21] 1 > 2 [Thu Feb 15:52:22] 2 > 3 [Thu Feb 02 1 5:52:22] 3 > 5 [Thu Feb 15:52:23] 5 > 6 [Thu Feb 15:52:24] 6 > d:codeex> |
I hope this article will help you with your Python programming.