Reputation: 1
I have a Moxa device that create Tcp-ip message from serial data and send them to me by LAN. i need to listen to hes specific external-ip(172.16.0.77) with python server. ill try to do this:
BUFFER_SIZE = 10000 # Normally 1024, but we want fast response
HOST = self.TCP_IP #(172.16.0.77)
PORT = self.TCP_PORT # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
print msg
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error as msg:
print msg
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
while s:
print s.getsockname()
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data:
self.emit(QtCore.SIGNAL("SamplesRecive"),data)
conn.close()
and i get : [Errno 10049] The requested address is not valid in its context could not open socket
I need to divide the serves to many Moxa devices so i cant use socket.INADDR_ANY
Any ideas?
Upvotes: 0
Views: 994
Reputation: 1510
socket.INADDR_ANY
equal to socket.bind('0.0.0.0')
if bind to "0.0.0.0" can listen all interfaces(which avaible)
Example of Moxa TCP :
import socket,time
import thread
#Example client
class _client :
def __init__(self):
self.status = False
def run(self,clientsock,addr):
while 1 :
try:
data = clientsock.recv(BUFF)
if data :
#do something with data
time.sleep(.1)
if self.status == False:
clientsock.close()
break
clientsock.send(next_query)
except Exception,e :
print e
break
client = _client()
ADDR = ("0.0.0.0", 45500) #so you need port how to decode raw socket data ?
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)#gain 50ms tcp delay
serversock.bind(ADDR)
serversock.listen(10)
While True :
clientsock, addr = serversock.accept()
if addr[0] == device_1_IP:
client.status = True
#start device1 thread(moxa is TCP client mode)
thread.start_new_thread(client.run, (clientsock, addr))
#if client.status = False you will be close connection.
But my offer is "use moxa with TCP server mode"
i am used 4x5450i 3x5250 over 120 device without any error.
Upvotes: 1