gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
使用Python实现tcp 104规约通信测试
- User
使用Python实现tcp 104规约通信测试
- Assistant
下面是一个使用Python Socket编程实现TCP 104规约通信测试的示例代码:
pythonimport socket # 设置主站IP和端口 server_ip = '192.168.0.1' server_port = 2404 # 设置本地IP和端口 local_ip = '192.168.0.2' local_port = 5555 # 创建Socket对象 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定本地IP和端口 client_socket.bind((local_ip, local_port)) try: # 连接到主站 client_socket.connect((server_ip, server_port)) # 发送测试数据 data = b'\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x01\x3F\x00\x04\x00\x00\x00\x01\x00\x0A\x00\x00' client_socket.sendall(data) # 接收数据 response = client_socket.recv(1024) print("Response:", response.hex()) except Exception as e: print("Error:", e) finally: # 关闭Socket连接 client_socket.close()在代码中,首先定义了主站的IP和端口,以及本地的IP和端口。然后创建了一个Socket对象,并绑定了本地IP和端口。接着使用
connect()方法连接到主站,并发送测试数据。最后,接收主站返回的数据并打印出来。注意要注意TCP 104规约通信的数据格式以及字节顺序的问题。