Use python3 to implement the TCP protocol, similar to UDP. UDP is used for real-time communication, while the TCP protocol is used to transmit files, commands and other operations, because these data are not allowed to be lost, otherwise it will cause file errors or command confusion. The following code simulates the client operating the server through the command line. The client enters a command, the server executes it and returns the result.
TCP (Transmission Control Protocol): It is a connection-oriented, reliable, byte stream-based transport layer communication protocol, defined by IETF's RFC 793.
TCP Client
from socket import *host = '192.168.48.128'port = 13141addr = (host,port) bufsize=1024tcpClient = socket(AF_INET,SOCK_STREAM) # 这里的参数和UDP不一样。tcpClient.connect(addr) #由于tcp三次握手机制,需要先连接while True: data = input('>>> ').encode(encoding="utf-8")if not data:break# 数据收发和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 = 13140bufsize = 1024addr = (host,port) tcpServer = socket(AF_INET,SOCK_STREAM) tcpServer.bind(addr) tcpServer.listen(5) #这里设置监听数为5(默认值),有点类似多线程。while True:print('Waiting for connection...') tcpClient,addr = tcpServer.accept() #拿到5个中一个监听的tcp对象和地址print('[+]...connected from:',addr)while True: cmd = tcpClient.recv(bufsize).decode(encoding="utf-8") print(' [-]cmd:',cmd)if not cmd:break###这里在cmd中执行来自客户端的命令,并且将结果返回###cmd = os.popen(cmd) ###os.popen(cmd)对象是file对象子类,所以可以file的方法cmdResult = cmd.read() cmdStatus = cmd.close()#################################################data = cmdResult if (not cmdStatus) else "ERROR COMMAND"tcpClient.send(data.encode(encoding="utf-8")) tcpClient.close() #print(addr,'End') tcpServer.close() #两次关闭,第一次是tcp对象,第二次是tcp服务器
The above is the detailed content of python3 implements simple server and client of TCP protocol. For more information, please follow other related articles on the PHP Chinese website!