Home > Backend Development > Python Tutorial > python3 implements simple server and client of TCP protocol

python3 implements simple server and client of TCP protocol

巴扎黑
Release: 2017-06-23 15:46:18
Original
1112 people have browsed it

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()
Copy after login

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服务器
Copy after login


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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template