Home Backend Development Python Tutorial How to use python3 to implement TCP protocol?

How to use python3 to implement TCP protocol?

Jun 16, 2017 am 10:51 AM

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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()

Copy after login

TCP Client


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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服务器

Copy after login

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to change tcp protocol in win11? Details of how to change tcp protocol in win11 system How to change tcp protocol in win11? Details of how to change tcp protocol in win11 system Feb 01, 2024 pm 05:30 PM

One of the transport protocols in Windows systems is the TCP protocol, which is required when running and using certain functions. Recently, some Win11 users have encountered problems with the TCP protocol and need to modify it. However, many people don’t know how to make successful modifications. In order to solve this problem, this Win11 tutorial will provide you with detailed setting methods. Please visit this site for the complete steps if you need them. How to change the TCP protocol in win11: 1. First, right-click the network icon in the lower right corner to open the network and internet settings. 3. Then open more network adapter options under relevant settings. 5. After opening, you can find the tcp protocol. Double-click it to open it. 7. You can also click Advanced to repair

TCP protocol and asynchronous IO processing technology in Go language TCP protocol and asynchronous IO processing technology in Go language Jun 02, 2023 am 09:10 AM

With the continuous development of Internet technology, TCP protocol and asynchronous IO processing technology have become increasingly important. As a modern programming language, Go language naturally supports TCP protocol and asynchronous IO processing technology, which makes Go language extremely convenient and efficient in developing network applications. This article will discuss the advantages of Go language in network application development from two aspects: TCP protocol and asynchronous IO processing technology. 1. TCP protocol The TCP protocol is a reliable, connection-oriented network transmission protocol. It can ensure the reliability of network transmission,

How to change TCP protocol settings in Windows 11 system How to change TCP protocol settings in Windows 11 system Apr 02, 2024 pm 01:43 PM

In the Windows 11 operating system, the TCP protocol, as a key part of the underlying communication architecture, plays an indispensable role in the stable operation of many functions in the system. When users intend to make personalized adjustments to the TCP protocol according to their own needs, they may face operational confusion. To this end, here are the detailed steps on how to change TCP protocol settings in Windows 11 system. Let’s take a look. Change method 1. Right-click the network icon in the taskbar in the lower right corner, and then select "Network and Internet Settings" in the option list. 2. After entering the new interface, click the "Advanced Network Settings" option on the right. 3. Then click "More Network Adapter Options" in "Related Settings". 4. of

How to install pip in python3 How to install pip in python3 Dec 20, 2023 pm 05:42 PM

Installation steps: 1. Make sure that Python3 has been installed and can be accessed through the command line; 2. Open the terminal and enter the "python3 -m ensurepip --upgrade" command to install pip; 3. Download the pip installation package from the official Python website; 4. Extract the downloaded pip installation package into a directory; 5. Open the terminal and navigate to the decompressed pip directory; 6. Run the "python3 setup.py install" command to install pip.

Which layer of protocol does tcp belong to? Which layer of protocol does tcp belong to? Jul 05, 2023 am 10:52 AM

tcp is a "transport layer" protocol. TCP refers to "Transmission Control Protocol", which is a connection-oriented, reliable, byte stream-based transport layer communication protocol. TCP complements the Internet Protocol. It defines the IP address used to identify systems on the Internet. It mainly Ensure end-to-end data transfer between different nodes.

Workerman development: How to implement instant messaging based on TCP protocol Workerman development: How to implement instant messaging based on TCP protocol Nov 07, 2023 am 10:34 AM

Workerman development: How to implement instant messaging based on TCP protocol Introduction: With the development of the Internet era, instant messaging plays an important role in our daily lives. Instant messaging based on the TCP protocol has become a common solution. This article will introduce how to use the Workerman framework to implement instant messaging based on the TCP protocol by writing specific code examples. 1. Introduction to Workerman Workerman is a high-performance PHPSocket service framework

Workerman development: How to implement file transfer based on TCP protocol Workerman development: How to implement file transfer based on TCP protocol Nov 07, 2023 am 09:14 AM

Workerman development: How to implement file transfer based on TCP protocol, specific code examples are required. Introduction: In today's Internet era, file transfer has become an indispensable part of daily work and life. File transfer based on TCP protocol is a method with high transmission efficiency and strong reliability. In this article, we will introduce how to use the Workerman framework to develop a file transfer service based on the TCP protocol, and provide specific code examples. 1. What is Workerman? Workerman

Workerman development: How to implement a remote file management system based on TCP protocol Workerman development: How to implement a remote file management system based on TCP protocol Nov 07, 2023 am 08:46 AM

Workerman development: How to implement a remote file management system based on TCP protocol Introduction: With the rise of cloud computing and remote work, remote file management systems have become the needs of more and more enterprises and individuals. In this article, we will introduce how to use the Workerman framework to implement a remote file management system based on the TCP protocol, and provide specific code examples. 1. Preparation Before starting to write code, we need to prepare some necessary tools and environment. First, make sure you have a PHP environment installed,

See all articles