SoFunction
Updated on 2025-03-04

Use Python to implement TCP/IP client and server communication functions

1. TCP/IP communication basics

TCP/IP (Transmission Control Protocol/Internet Protocol) is the basic protocol of the Internet, used to conduct reliable data transmission between computers in the network. In Python, you can usesocketmodule to realize TCP/IP communication.

2. Implement TCP/IP server

import socket
 
def start_server(host='127.0.0.1', port=65432):
    """
     Start a TCP/IP server
     :param host: The IP address listened to by the server, default to the local loopback address
     :param port: The port that the server listens
     """
    with (socket.AF_INET, socket.SOCK_STREAM) as s:
        ((host, port))
        ()
        print(f"Server listening on {host}:{port}")
        conn, addr = ()
        with conn:
            print(f"Connected by {addr}")
            while True:
                data = (1024)
                if not data:
                    break
                print(f"Received from client: {()}")
                (data)  # Echo back the received data
 
if __name__ == "__main__":
    start_server()

Code explanation

  • (socket.AF_INET, socket.SOCK_STREAM): Create a TCP socket.
  • ((host, port)): Bind IP address and port.
  • (): Start listening to the connection.
  • conn, addr = (): Accepts a connection, returning a new socket object and client address.
  • (1024): Receive data, up to 1024 bytes.
  • (data): Send the received data back to the client.

3. Implement TCP/IP client

import socket
 
def start_client(host='127.0.0.1', port=65432):
    """
     Start a TCP/IP client
     :param host: The IP address of the server
     :param port: server port
     """
    with (socket.AF_INET, socket.SOCK_STREAM) as s:
        ((host, port))
        while True:
            message = input("Enter a message to send: ")
            (())
            data = (1024)
            print(f"Received from server: {()}")
 
if __name__ == "__main__":
    start_client()

Code explanation

  • (socket.AF_INET, socket.SOCK_STREAM): Create a TCP socket.
  • ((host, port)): Connect to the server.
  • (()): Send data to the server.
  • (1024): Receive data sent by the server.

4. Suggestions on rational use in daily development

  1. Error handling: In practical applications, network communication may encounter various errors, such as connection interruption, timeout, etc. Should be usedtry-exceptblocks to catch and handle these exceptions.
  2. Multithreaded/multiprocess: For high concurrency scenarios, multiple threads or multiple processes can be used to handle multiple client connections.
  3. Heartbeat mechanism: In order to detect the survival status of the client, a heartbeat mechanism can be added to the communication.
  4. Data encryption: For the transmission of sensitive data, SSL/TLS should be considered for encryption.

5. Points to be noted during the actual development process

  1. Resource Management: Make sure that sockets and other resources are closed correctly after communication is over to avoid resource leakage.
  2. Data format: When sending and receiving data, the format of the data (such as JSON, XML, etc.) should be clarified, and the corresponding serialization and deserialization operations should be performed.
  3. Timeout setting: Set a reasonable timeout time to avoid performance problems caused by long waits.
  4. Logging: Record key information during the communication process, which is easy to debug and troubleshoot.

6. Error handling example

import socket
 
def start_server(host='127.0.0.1', port=65432):
    with (socket.AF_INET, socket.SOCK_STREAM) as s:
        ((host, port))
        ()
        print(f"Server listening on {host}:{port}")
        while True:
            try:
                conn, addr = ()
                with conn:
                    print(f"Connected by {addr}")
                    while True:
                        data = (1024)
                        if not data:
                            break
                        print(f"Received from client: {()}")
                        (data)
            except Exception as e:
                print(f"Error: {e}")
 
if __name__ == "__main__":
    start_server()

Code explanation

  • usetry-exceptThe block catches possible exceptions and prints error messages.

7. Multithreaded Example

import socket
import threading
 
def handle_client(conn, addr):
    with conn:
        print(f"Connected by {addr}")
        while True:
            data = (1024)
            if not data:
                break
            print(f"Received from client: {()}")
            (data)
 
def start_server(host='127.0.0.1', port=65432):
    with (socket.AF_INET, socket.SOCK_STREAM) as s:
        ((host, port))
        ()
        print(f"Server listening on {host}:{port}")
        while True:
            conn, addr = ()
            thread = (target=handle_client, args=(conn, addr))
            ()
 
if __name__ == "__main__":
    start_server()

Code explanation

  • useCreate a new thread for each client connection to implement concurrent processing.

8. Example of heartbeat mechanism

import socket
import time
 
def start_client(host='127.0.0.1', port=65432):
    with (socket.AF_INET, socket.SOCK_STREAM) as s:
        ((host, port))
        while True:
            message = input("Enter a message to send: ")
            (())
            data = (1024)
            print(f"Received from server: {()}")
            (5)  # Send a heartbeat every 5 seconds
            (b"heartbeat")
 
if __name__ == "__main__":
    start_client()

Code explanation

  • A heartbeat message is sent every 5 seconds to detect the client's survival status.

Through the above examples and explanations, I hope you can better understand and implement TCP/IP client and server communications, and apply this knowledge in actual development.

The above is the detailed content of using Python to implement TCP/IP client and server communication functions. For more information about Python TCP/IP client and server communication, please pay attention to my other related articles!