current position:Home>Implementation of workstation monitoring system with Python socket

Implementation of workstation monitoring system with Python socket

2022-05-15 02:46:48Wei Yunshu

1、 Demand analysis

Use python Realize workstation monitoring system , It is divided into data acquisition end ( client ) And the server side , Among them, the data acquisition end collects a copy of data every other period of time and uploads it to the server , And get feedback from the server ; The server obtains the data information collected by the client , We're going to process it , Then send feedback . There are multiple clients , Need the ability of the server to handle multiple requests concurrently .
 Insert picture description here

2、 The overall architecture

  • The server uses Alibaba cloud server , Yes, the public network IP, The whole network can access
  • Data collector , Here we use ubuntu16.04、win7、win10 These three machines do simulation , Upload data to the server
     Insert picture description here

3、 The implementation of the server

Step1: Apply for Alibaba cloud server
Step2: Set the external port in the firewall of ECs
 Insert picture description here
Step3: Open the corresponding port in the cloud server
 Insert picture description here

4、 The implementation of client

5、socket

  • socket It belongs to the transport layer (TCP/UDP) And application layer ( User process ) In between .
  • Let users directly block TCP/IP Protocol family , Pay attention to the transmission of data .
  • And requests In the library HTTP The request is slightly different , But they all realize the transmission of data between the client and the server .
  • stay python Call directly socket library .
     Insert picture description here
  • socket The workflow is as follows
     Insert picture description here
  • Start with the server . Initialize the server first Socket, And then bind to the port (bind), Listen to the port (listen), call accept Blocking , Wait for the client to connect . At this time, if there is a client initializing a Socket, And then connect to the server (connect), If the connection is successful , At this time, the connection between the client and the server is established . Client sends data request , The server receives the request and processes it , Then send the response data to the client , Client reads data , Finally, close the connection , An interaction ends .

6、 Program code

# === TCP Server program  server.py ===
import socket
import threading

def clientHandler(dataSocket,addr):
    while True:
        recved = dataSocket.recv(1024)
        if not recved:
            print('client %s close link'% addr)
            break
        info = recved.decode()
        print('recved info from %s: %s'% (addr,info))
        dataSocket.send(('service recive the info %s '% info).encode()) #  The data type sent must be bytes, So code 
    dataSocket.close()

def socket_service():
    IP = "*.*.*.*"      #  Server's IP Address 
    PORT = 6666         #  The port number used by the socket 
    BUFLEN = 1024   #  Define once from socket The maximum number of reads in the cache is 512 Bytes of data 

    #  Instantiate a socket object ,
    #  Parameters AF_INET  It means that we should socket The network layer uses IP agreement 
    #  Parameters SOCK_STREAM  Express socket The transport layer uses TCP agreement 
    listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listenSocket.bind((IP,PORT))  # socket Bind the address and port 
    listenSocket.listen(10)     #  send socket In a listening state , Wait for the client's connection request , Parameters 10 Indicates the maximum number of clients waiting to connect 
    print('Waiting connection...')
    while True:
        dataSocket,addr =  listenSocket.accept()
        print('Client %s link suceess :'% addr)
        th = threading.Thread(target=clientHandler,args=(dataSocket,addr))  #  Multithreading , It can receive requests from multiple clients at the same time 
        th.start()
    listenSocket.close()

if __name__=='__main__':
    socket_service()
# === TCP  Client program  client.py ===

import socket
import time,datetime
import psutil
import json

def socket_client():
    IP = "*.*.*.*"
    SERVER_PORT = 6666
    BUFLEN = 1024

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    #  Connect to server  IP:PORT
    s.connect(('*.*.*.*',6666))

    while True:
        time.sleep(4)     #  Pause 4 second 
        data = psutil.virtual_memory()      # Read computer information 

        #  Express the information as something like json Format 
        info = [{
    
                "time":datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S'),
                "save":data.percent,
                "cpu":psutil.cpu_percent(interval=1)
                }]
        jsonstr = json.dumps(info)   #  Generate data json Format 
        data = jsonstr.encode()     #  Code the data 
        s.send(data)        # Transfer data to the server 
        print(s.recv(1024))     # Print the information returned by the server 
    #  Close the connection 
    s.close()

if __name__=='__main__':
    socket_client()

7、 Experimental results and Analysis

7.1 Server experiments

 Insert picture description here
There are two data acquisition terminals that send data information to the server , The program has run 4 Hours , After testing , More stable

7.2 Client experiment

 Insert picture description here
The client can better accept the data of the server

7.3 experimental analysis

advantage :

  • It can realize multiple data acquisition terminals in the LAN to transmit information to the server , And can receive the feedback information from the server , It takes to be able to preliminarily complete the experiment

shortcoming :

  • Data is transferred to the server , Store this data as txt、json、xml Waiting for documents is not very good , You need to keep opening files 、 Reading and writing 、 close , It's not reasonable to , Need to store to mysql In the database , but python Direct manipulation mysql The database is not very convenient , There is a need to improve

improvement :
It doesn't use socket Achieve communication , May adopt request library , adopt http Mode transmission json Data and file data to the server , Use in the server background django Service implementation of architecture and background transmission , adopt restframework Realize data reading .

copyright notice
author[Wei Yunshu],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/132/202205120516295593.html

Random recommended