user1631534
user1631534

Reputation: 15

python Socket send ascii command and receive response

I am trying to establish connection to a ADAM-4017+ I/O module over the network using a Lantronix EDS2100 module through socket communication in python. For the life of me I cannot get it to work.

The EDS has an IP address and a port (10001) that the adam unit is connected to. I am trying to query the adam for the value of ch 1 (ascii command is #000)

Any help greatly appreciated:

import socket
edsIP = "192.168.1.135"
edsPORT = 10001
MESSAGE="#000\r"


srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
srvsock.bind( ('',23000))
srvsock.listen(1)
newsock, (remhost, remport) = srvsock.accept()
srvsock.send((MESSAGE),(edsIP, EdsPORT) )



 while 1:


    data, addr = srvsock.recv(4096) 
    print ("received message:", data,addr)
    srvsock.close()

Upvotes: 1

Views: 21268

Answers (2)

jdi
jdi

Reputation: 92569

I don't know anything about this device specifically, but from your description, you said its expecting a connection on port 10001. But what you are doing in your code is opening your own socket and listening for connections on port 23000, and then waiting for connections. If you aren't expecting something to connect to you, then you will just be waiting for no reason.

If all your device needs is for you to connect and send a message, then I would think this would do it:

import socket

edsIP = "192.168.1.135"
edsPORT = 10001
MESSAGE="#000\r"

srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srvsock.settimeout(3) # 3 second timeout on commands
srvsock.connect((edsIP, edsPORT)))
srvsock.sendall(MESSAGE)

data = srvsock.recv(4096) 
print "received message:", data

srvsock.close()

Update

Your comments suggest you might be using python3. If so, you may have to adjust the code like this:

MESSAGE=b'#000\r'

And when you receive your bytes response, if you want to turn it into a string:

print data.decode("UTF-8")

Upvotes: 2

Daniel Figueroa
Daniel Figueroa

Reputation: 10666

The only problem i can see directly is that you have indented the while statement with one space, but thats probably just from cutting and pasting in here.

After some testing It's clear that when you try to accept on the serversocket it will block, so you're never sending anything to your device.

Upvotes: 0

Related Questions