Python3 implements TCP simple server and client cases (SHARE), python3tcp
Use python3 to implement the TCP protocol, which is similar to UDP.UDP is used for timely communication, while TCP is used to send files, commands, and other operations, because the data cannot be lost, otherwise it may cause file errors or command chaos. The following code simulates the client's operations on the server through the command line. The client enters the command, and the server executes the command and returns the result.
TCP (Transmission Control Protocol ):It is a connection-oriented, reliable, byte stream-based transport layer communication protocol, defined by RFC 793 of IETF.
TCP client
From socket import * host = '192. 168.48.128 'port = 192 addr = (host, port) bufsize = 13141 tcpClient = socket (AF_INET, SOCK_STREAM) # The parameters here are different from those in UDP. TcpClient. connect (addr) # because of the tcp three-way handshake mechanism, you must first connect while True: data = input ('>>> '). encode (encoding = "UTF-8") if not data: break # The data sending and receiving are basically the same as the UDP tcpClient. send (data) data = tcpClient. recv (bufsize ). decode (encoding = "UTF-8") print (data) tcpClient. close ()
TCP client
From socket import * from time import ctimeimport OS host = ''port = 13140 bufsize = 1024 addr = (host, port) tcpServer = socket (AF_INET, SOCK_STREAM) tcpServer. bind (addr) tcpServer. listen (5) # set the number of listeners to 5 (default), which is similar to multithreading. While True: print ('Waiting for connection... ') tcpClient, addr = tcpServer. accept () # obtain the tcp object and address print ('[+]... connected from: ', addr) while True: cmd = tcpClient. recv (bufsize ). decode (encoding = "UTF-8") print ('[-] cmd:', cmd) if not cmd: break ### run commands from the client in cmd, and return the result ### cmd = OS. popen (cmd) ### OS. the popen (cmd) object is a subclass of the file object, so you can use the file method cmdResult = cmd. read () slave status = cmd. close () ######################################## ######### data = cmdResult if (not ready status) else "error command" tcpClient. send (data. encode (encoding = "UTF-8") tcpClient. close () # print (addr, 'end') tcpServer. close () # close twice. The first is a tcp object and the second is a tcp server.
The above simple server and client case (SHARE) of python3 to implement TCP protocol is all the content that I have shared with you. I hope to give you a reference and support for more customers.