Python-TCP/IP通信

2024-09-30 00:35:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的python-modbus-tcp通信代码,它在这条线上等待,然后停止连接,我的错误是:

sock.connect((TCP_IP, TCP_PORT))

(如果我使用从程序也不工作) 在我的客户端,我使用以下代码:

^{pr2}$

这是主界面:

# Create a TCP/IP socket
TCP_IP = '10.0.2.2'
TCP_PORT = 502
BUFFER_SIZE = 39
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((TCP_IP, TCP_PORT))



try:

    unitId = 16  # Plug Socket11
    functionCode = 3  # Write coil

    print("\nSwitching Plug ON...")
    coilId = 1
    req = struct.pack('12B', 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, int(unitId), 0x03, 0xff, 0xc0, 0x00,
                  0x00)
    sock.send(req)
    print("TX: (%s)" % req)
    rec = sock.recv(BUFFER_SIZE)
    print("RX: (%s)" % rec)
    time.sleep(2)

    print("\nSwitching Plug OFF...")
    coilId = 2
    req = struct.pack('12B', 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, int(unitId), 0x03, 0xff, 0xc0, 0x00,
                  0x00)
    sock.send(req)
    print("TX: (%s)" % req)
    rec = sock.recv(BUFFER_SIZE)
    print("RX: (%s)" % rec)
    time.sleep(2)

finally:
    print('\nCLOSING SOCKET')
    sock.close()

Tags: 代码ipsizeportbufferconnectsocketreq
2条回答

我认为您的问题是IP地址:10.0.2.2,如这里所述[Connection to LocalHost/10.0.2.2 from Android Emulator timed out。 您可以将'10.0.2.2'替换为'localhost',或者尝试查找您的IPv4地址。在

为此,如果使用Linux,请在命令提示符下键入ifconfig,或者在windows中键入ipconfig并搜索IPv4地址。在

我使用了一个简单的客户机-服务器示例来运行代码,并将'10.0.2.2'替换为'localhost',一切正常。在

服务器端:

import socket
import struct
import time

TCP_IP = 'localhost'                 
TCP_PORT = 502
BUFFER_SIZE = 39

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
sock, addr = s.accept()
print 'Connected by', addr
try:
    unitId = 16  # Plug Socket11
    functionCode = 3  # Write coil

    print("\nSwitching Plug ON...")
    coilId = 1
    req = struct.pack('12B', 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 
    int(unitId), 0x03, 0xff, 0xc0, 0x00,
    0x00)
    while 1:
        sock.send(req)
        print("TX: (%s)" % repr(req))
        rec = sock.recv(BUFFER_SIZE)
        print("RX: (%s)" % repr(rec))
        time.sleep(2)
        break

    print("\nSwitching Plug OFF...")
    coilId = 2
    req = struct.pack('12B', 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 
    int(unitId), 
    0x03, 0xff, 0xc0, 0x00,
    0x00)
    while 1:
        sock.send(req)
        print("TX: (%s)" % repr(req))
        rec = sock.recv(BUFFER_SIZE)
        print("RX: (%s)" % repr(rec))
        time.sleep(2)
        break
finally:
    sock.close()

客户端:

^{pr2}$

确保在不同的文件/终端中运行服务器和客户端

我想你的问题是“为什么插座连接()呼叫挂断?“。这是因为默认情况下,它会无限期地等待连接。换句话说,默认情况下,调用是“阻塞”的。如果您只想等待最多500毫秒的连接,则需要指定:

sock.connect(.5) #wait 500 milliseconds for a connection attempt

另请参见Python socket connection timeout

相关问题 更多 >

    热门问题