Home  >  Article  >  Backend Development  >  How to use python3 to implement TCP protocol?

How to use python3 to implement TCP protocol?

零下一度
零下一度Original
2017-06-16 10:51:482010browse

The following editor will bring you a simple server and client case (share) of implementing TCP protocol in python3. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

Use python3 to implement the TCP protocol, which is similar to UDP. UDP is used for timely 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): is a connection-oriented, reliable, byte stream-based transport layer communication protocol, developed by IETF Definition of RFC 793.

TCP Client


from socket import *

host = '192.168.48.128'
port = 13141
addr = (host,port)
bufsize=1024

tcpClient = 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 ctime
import os 

host = ''
port = 13140
bufsize = 1024
addr = (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 How to use python3 to implement TCP protocol?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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