SoFunction
Updated on 2024-10-30

Python implementation of multi-threaded/multi-process TCP server

Multi-threaded TCP servers, for your reference, are as follows

Background: the student company's sensor devices need to send the collected data to the server, want to write a simple server to test the use of the effect of the device to collect data is very important, so consider the use of TCP protocol to achieve.

Because it's just for testing, it's multi-threaded, after all, it saves resources (the use of concatenation will lead to I/O blocking)

Opened the door and moved right on up

I. tcp_server_v1.0 instructions for use:

1. Running environment: python3 interpreter, and install socket, threading module;
2. This version uses multithreaded implementation of multitasking;
3. Support multiple devices to connect and provide services at the same time.

II. Code logic:

Specify the server operating port as: 8125
Create a server class
Instantiate a server object
The server object calls the methods in the class

1 Initialize server properties (def __init__)

1.1 Creating Sockets
1.2 Resolve program port occupancy issues
1.3 Bind local ip address
1.4 Changing a socket to a listening socket with a maximum number of connections of 100

2 Define the device connection method (def run_forever)

2.1 Entering the cycle
2.2 Waiting for the device to connect...
2.2.1 When the device is connected, print the ip and port of the device.
2.2.2 Create a thread to invoke the business processing methods to service the device

3 Business Processing Method (def service_machine)

3.1 Entering the cycle
3.2 Waiting for the receiving device to send data...

3.2.1 When the server receives data
3.2.2 Determining whether data is empty
No: Print the data content, perform business processing, and return the processed data results to the device
Yes: the print device disconnects, exits the loop, and closes the socket

The code is implemented as follows:

#!C:\Python3.6.5\
# -*- coding: gbk -*-

import socket
import threading

class WSGIServer(object):
 def __init__(self, port):
 """Initialization objects"""
 # Create sockets
 self.tcp_server_socket = (socket.AF_INET, socket.SOCK_STREAM)
 # Resolve program port occupancy issues
 self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 # Bind the local ip address
 self.tcp_server_socket.bind(("", port))
 # Turn sockets into listening sockets, maximum number of connections is 100
 self.tcp_server_socket.listen(100)

 def run_forever(self):
 """Device Connection"""
 while True:
 # 1. wait for device to connect (establish tcp connection via ip address and port)
 # If a device is connected, a socket is generated for communication between the device and the server: new_socket
 # will get the ip address and port of the device
 new_socket, client_addr = self.tcp_server_socket.accept()
 print("installations{0}connected".format(client_addr))

 # 2. Creating threads to handle the demands of the device
 t1 = (target=self.service_machine, args=(new_socket, client_addr))
 ()

 def service_machine(self, new_socket, client_addr):
 """Business Processing"""
 while True:
 # 3. Receive data sent by the device, maximum 1024 bytes in a single pass, decoded in 'gbk' format
 receive_data = new_socket.recv(1024).decode("gbk")
 # 4. If the data sent by the device is not empty
 if receive_data:
 # 4.1 Print the received data, here you can write the data sent by the device to a file
 # Get device ID information
 print(receive_data)
 if receive_data[0:6] == "report":
  response = "SET OK:" + receive_data
 else:
  receive_data = receive_data[6:].split(",")[0]
  # Splice the response data
  response = "alarm=" + receive_data + ",Switch:clear"
 print(response)
 # 4.2 Return original data as answer, encoded in 'utf-8' format
 new_socket.send(("utf-8"))
 # 5. When the device is disconnected, null byte data is received to determine that the device is disconnected
 else:
 print('installations{0}Disconnect...'.format(client_addr))
 break

 # Close the socket
 new_socket.close()


def main(port):
 """Create a WEB server."""
 wsgi_server = WSGIServer(port)
 print("The server is on.")
 wsgi_server.run_forever()



if __name__ == '__main__':
 port = 8125 # Specify the port
 main(8125)

This is the whole content of this article.