Python TCP sending and receiving information

A brief introduction to several knowledge points

  1. TCP: transmission control protocol is a connection oriented, byte stream based transport layer communication protocol. This connection is one-to-one, so TCP is not suitable for broadcast applications. For broadcast based applications, please use UDP protocol.
  2. Socket: socket is a module, which we use to send and receive information
  3. Network protocol version: IPV4 and ipv6, because the latter has not yet been popularized, all of which are still commonly used now
  4. ip, and port: write the ip to whom you want to send (write your own local ip here, and if you don't know, open cmd and input ipconfig to view); use any port number (except famous port)
  5. Encode: encode. Convert the string to bytes because of the format of sendto method

2. TCP receiving information (TCP server):

Because the tcp protocol is a one-to-one connection, create a server to receive information first
In short, there are six steps

  1. Import socket module
  2. Create a TCP socket
  3. Binding ip and port
  4. The maximum number of concurrent receivers set to passive listening mode is 128 (only when listening mode is set can it be a server)
  5. Waiting to receive the link request is a tuple (the socket object of the client contains: (address and port of the client))
  6. Close socket

Look at the code directly below: ↓ (turn off WiFi during test due to ip problem)

# Guide bag
import socket

# 2 initialize socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 3 server binding ip and port
tcp_socket.bind(('192.168.52.1', 12000))

# 4 the maximum number of concurrent receivers set to passive listening mode is 128
tcp_socket.listen(128)

# 5 wait for receiving link request to receive a tuple (client's socket object, (client's address, port))
client, addr = tcp_socket.accept()


# To receive, you need to use the socket object of the client to receive, because it is sent with its object
data = client.recv(1024)

# The format of sending is byte. To decode, decode() defaults to gbk
print(data.decode())

# 6 disconnect
tcp_socket.close()

Here is a network debugging assistant, in Baidu network disk, 2M, for testing ↓
https://pan.baidu.com/s/1_hVVoee7InHbyIA1eVZKhA

Three TCP sending data (TCP client)

The client is to send data to the server, so it's easy to understand
To summarize the steps:

  1. Import socket module
  2. Create a TCP socket
  3. Establish a connection (with the server)
  4. Sending data
  5. Close socket

Look at the code:

# 1 guide pack 
import socket

# 2 initialize socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 3. Set up a link to the server ip and port to be passed in the link
tcp_socket.connect(('192.168.52.1', 11000))

# 4 send data
tcp_socket.send('Ha ha ha ha ha'.encode())

# 5 disconnect
tcp_socket.close()

Now that the client and the server are available, let's improve the code

1. Improve the server code:

First of all, the server can't finish receiving data only once, so add a loop and accept all the time

import socket

# 1 initialize socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# The set address can be reused, which solves the problem that the port is not released in time
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

# 2 server binding ip and port
tcp_socket.bind(('192.168.52.1', 12000))

# 3 the maximum number of concurrent receivers set to passive listening mode is 128
tcp_socket.listen(128)

while True:
    # 4 wait for receiving link request to receive a tuple (socket object of client, (address and port of client))
    client, addr = tcp_socket.accept()
    print('client:', client)
    print('addr:', addr)

    while True:
        data = client.recv(1024)
        print(data.decode('gbk'))
        if not data:
            # If the data is empty, it means that the client has closed the link, and the client here can also close
            client.close()
            break

# 5 disconnect
tcp_socket.close()

Let's say: the client (client sent: client socket object) received by the server is sent by the client. When we reply, we also reply with this socket object. Think about it. If there are multiple clients sending data at the same time? It's ok, because it processes each socket (client object) Many people call manual customer service, and they will internally assign a customer service to communicate with you.)

2. Improve the client code:

The client can send data with socket object or receive data with socket (because the server receives data with socket object of the client)

import socket

# 1 initialize socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 2. Set up the ip and port of the server to be linked in
tcp_socket.connect(('192.168.52.1', 11000))

while True:
    text = input('Data sent')
    # 3 send data
    tcp_socket.send(text.encode('gbk'))
    # 4 receiving data
    data = tcp_socket.recv(1024)
    print(data.decode('gbk'))

# 5 disconnect
tcp_socket.close()

When testing, pay attention to the coding format, address problem and port problem, which are different according to your own situation

At the end of the article, I will talk about the differences between TCP and UDP

  • Connection oriented (confirm that a three-way handshake has been created and the connection has been created before transmission.)
  • Orderly data transmission
  • Resend lost packets
  • Discard duplicate packets
  • Error free data transmission
  • Blocking / flow control

There is also a small case of TCP: TCP download file

Published 11 original articles, won praise 6, visited 147
Private letter follow

Tags: socket network

Posted on Thu, 06 Feb 2020 23:12:56 -0800 by carlg