Phyton Socket发送接收Modbus数组

需要用Phyton发送Modbus数据包,找了网上的资料,例子如下,功能时不停的打开服务器的端口,然后读取数据,用来测试服务器的性能。

 

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

import socket
import time
import struct
MaxBytes=1024*1024
host ='192.168.0.61'
port = 502
arr = [0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20]
data=struct.pack("%dB"%(len(arr)),*arr)

num = 0
while True:
    num=num+1
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(30)
    client.connect((host, port))

    sendBytes = client.send(data)
    if sendBytes<=0:
        break;
    recvData = client.recv(MaxBytes)
    if not recvData:
        print('接收数据为空,我要退出了')
        break
    print("成功打开端口数量:", num)
    localTime = time.asctime( time.localtime(time.time()))
    print(localTime, ' 接收到数据字节数:',len(recvData))
    '''print(recvData.decode()) '''
client.close()
print("我已经退出了,后会无期")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

你可能感兴趣的:(嵌入式硬件,Modbus)