Could you please give me some advise on this piece of code?

Ian Kelly ian.g.kelly at gmail.com
Mon Sep 12 19:41:06 CEST 2011


On Mon, Sep 12, 2011 at 8:51 AM, G. <bestenborstel at gmail.com> wrote:
> When I start LabView UDP_sender.vi it is supposed to send a string
> back to python, but sometimes it ends with an error saying the port
> and the ip is already in usage. Do I have to start first LabView or
> the python scrip when listening to LabView, please?

If LabView is sending, then the Python script should already be
receiving, so start Python first.

> def openUDPSocket(UDP_IP,UDP_PORT):
>    #UDP_IP="127.0.0.1"
>    #UDP_PORT=5005
>    print "Creating socket ..."
>    sock=socket.socket( socket.AF_INET, # Internet
>                        socket.SOCK_DGRAM ) # UDP

I don't think this is sufficient to create a UDP socket.  To be safe,
you should specify the protocol as well:

sock = socket.socket(socket.AF_INET,
    socket.SOCK_DGRAM, socket.IPPROTO_UDP)

>    #sock.bind((UDP_IP,UDP_PORT))

Your bind call is commented out, which means that your socket will be
bound to an arbitrary port selected by the OS.  This will make it hard
for LabView to send it messages, since it won't know what port to use.

Also, you appear to be using the same address and port for both
endpoints.  The UDP socket in Python and the UDP socket in LabView
should be bound to two separate ports.  This is probably why you were
getting the "port already in use" error, before you commented this
out.

>    #sock.listen(1)

You don't need this at all.  listen() is for TCP sockets.

> def fastPump(sock):
>    # Start pumping and return
>    MESSAGE="pumpfast"
>
>   # print "UDP target IP:", UDP_IP
>   # print "UDP target port:", UDP_PORT
>   # print "message:", MESSAGE
>
>    sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )

The IP and port here should be that of the destination, i.e. the
address of the LabView socket.

> counter_while_loop=0
> print "test"
> while counter_while_loop < 3:
>        data,addr = pumpsocketUDP.recvfrom(1024)
>        print "test"
>        if not data:
>                print "Client has exited!"
>                break
>        else:
>                print "\nReceived message '", data,"'"
>        counter_while_loop=counter_while_loop+1

You should really use a for loop here:

for counter in range(3):
    data, addr = pumpsocketUPD.recvfrom(1024)
    print "Received message %r" % data

Note that if data is empty, it means that it received an empty
message, not that the client has exited.  It may be that you're having
the LabView client send an empty message when it exits, but this does
not happen automatically.

HTH,
Ian



More information about the Python-list mailing list