Search code examples
pythonpython-3.xsocketstcp

trying to receive data from remote device using udp socket


I'm trying to send a command to a remote device: E5071C ENA Vector Network Analyzer

These are my problems:

  • When I try to send and receive data from the socket, it "hangs".

  • I am not sure which type of socket I should use.

For the other commands, I used s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM), but I only had to send data in those cases. Here I need to send and receive data. I have tried to use a while Trueloop like this:

while True:
    s.settimeout(1)
    print(sys.stderr, 'waiting for a connection')
    connection, client_address = s.accept()
    try:
        print(sys.stderr, 'client connected:', client_address)
        while True:
            data = connection.recv(1024)
            print(sys.stderr, 'received "%s"') % data
            if data:
                connection.sendall(data)
            else:
                break
    finally:
        connection.close()

I could not get the result I wanted with the while loop either, so this is what I have so far instead:

## import modules
## for loop iterations
## commands sent to remote device using UDP socket

def is_hanging(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host,port))
    min_msg = ':CALCulate:SELected:MARKer:FUNCtion:TYPE MINimum'
    s.send(min_msg.encode())
    s.settimeout(1)
    try:
        s.recv(1024)
        print("Received data!")
        return True
    except socket.timeout as e:
        print(e)
        return False
    finally:
        s.close()

if is_hanging('10.5.33.16',5025) is True:
    pass
else:
    raise Exception("Could not receive data.")

I am not entirely sure how s.recv works, but I what I am hoping/expecting is that data I send to the remote device generates a response which sent back to me. Right now it is just hanging.


Solution

  • socket.accept() is only relevant in the context of a stream-based socket that's been configured as a listening socket. It doesn't make sense to use on a datagram socket, especially one that's already associated with a remote host.

    (Are you sure SOCK_DGRAM -- i.e. UDP -- is correct here? Most SCPI devices I've worked with use TCP, i.e. SOCK_STREAM.)

    If you're sure that you're using the right protocol, remove the call to s.accept(), and call .recv() on the existing socket s.