Python - [socket] Simple example of client reconnection processing Demo (1)

I. Introduction

In Python, when using socket for network communication, if the connection is disconnected, you can implement reconnection processing through the following steps

2. Sample code

1. Define a function to establish a socket connection

import socket

def connect_socket(host, port):
    while True:
        try:
            # 建立socket连接
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((host, port))
            print('Socket connected')
            return sock
        except socket.error as e:
            print('Socket error:', e)
            time.sleep(5)

This function uses a while loop to continuously try to establish socketa connection. If socket.erroran exception occurs, it prints the exception information and waits 5 seconds to try again. When the connection is successful, the function returns a connection socket.

2. Use the connection function in the main program

In the main program, you can use the connection function defined above to establish a socket connection. If the connection is disconnected, the program will automatically reconnect, as shown below:

def main():
    host = 'example.com'
    port = 8888
    sock = connect_socket(host, port)

    # 循环处理数据
    while True:
        try:
            # 从socket中读取数据
            data = sock.recv(1024)

            # 处理数据
            ...

        except socket.error as e:
            print('Socket error:', e)
            sock = connect_socket(host, port)

In this program, the socket connection is first established through the connection function and the connection socket is saved in the variable sock. Then it enters an infinite loop to read data from the socket and process it. Once a socket.error exception occurs, it means that the connection has been disconnected. At this time, the program will call the connection function to reconnect. After the reconnection is successful, the program will continue to read data.

3. Complete code:

import socket
import time


def connect_socket(host, port):
    while True:
        try:
            # 建立socket连接
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((host, port))
            print('Socket connected')
            return sock
        except socket.error as e:
            print('Socket client reconnect =====> {}, Socket error:{}'.format('5s', e))
            time.sleep(5)


def main(host, port):
    sock = connect_socket(host, port)

    # 循环处理数据
    while True:
        try:
            # 从socket中读取数据
            data = sock.recv(1024)

            # 处理数据
            ...

        except socket.error as e:
            print('Socket recv data error:', e)
            sock = connect_socket(host, port)


if __name__ == '__main__':
    host = '127.0.0.1'
    port = 8080
    # connect_socket(host, port)
    main(host, port)

3. Run the program

Execute the following command in the terminal to run the Python program

python3 socket_client.py

When the server is not started and the client is started and connected to the server, the abnormal effect is as follows:
Insert image description here

In this way, socket reconnection processing can be implemented through a connection function. When the connection is disconnected, the program will automatically reconnect, thus ensuring the continuity of network communication.

The above is an example of how to handle abnormal client reconnection in Python using socket client. I hope it will be helpful to you!

Guess you like

Origin blog.csdn.net/qq_43030934/article/details/132124745