python3 implements TCP protocol for simple server and client case of sharing

  • 2020-06-03 07:14:42
  • OfStack

python3 is used to implement the TCP protocol, similar to UDP. UDP is used for instant communication, while the TCP protocol is used to transmit files, commands, and so on, because this data is not allowed to be lost, which would cause file errors or command confusion. The following code simulates the client operating the server from the command line. The client enters the command, the server executes it and returns the result.

TCP (Transmission Control Protocol Transport Control Protocol) is a connection-oriented, reliable, byte flow-based transport layer communication protocol, defined by RFC 793 of IETF.

TCP client


from socket import *

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

tcpClient = socket(AF_INET,SOCK_STREAM) #  The sum of the parameters here UDP Don't 1 The sample. 
tcpClient.connect(addr) # Due to the tcp3 Second handshake mechanism, need to connect first 

while True:
  data = input('>>> ').encode(encoding="utf-8")
  if not data:
    break
  #  Data transceiver and UDP basic 1 to 
  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) # Here we set the number of listeners to be 5( The default value ), It's kind of like multithreading. 

while True:
  print('Waiting for connection...')
  tcpClient,addr = tcpServer.accept() # get 5 it 1 A listener 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
    ### Here in cmd Executes the command from the client and returns the result ###
    cmd = os.popen(cmd) ###os.popen(cmd) The object is file Object subclass, so you can file The method of 
    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() # Twice closed, No 1 Time is tcp The object, the first 2 Time is tcp The server 

Related articles: