UDP Connections

Top  Previous  Next

UDP Connections are different from the TCP, SSL and Serial connections. The main difference is that UDP is connectionless and that it's not stream oriented. Data always arrives in blocks or not at all. Thus there is no need for a parser as with the other connections. This means the API is a little different.

 

To create a UDP connection use:

 

connection = transport.udp( callback )

 

Callback is a lua function that will receive the data, address and port for the remote device.

 

function callback( data, address, port )

 print(data,address,port)

end

 

the UDP connection object has a few methods.

 

Return

Signature

Description

number

send( data, address, port )

sends the data to the remote device

 

close

closes the socket

boolean

listen( port )

listens on the port for data.

boolean

joinMulticastGroup( group )

joins a multicast group. Note this must be called after the socket is listening.

 

please note that address should be an IP address, not a hostname. You can get the IP address by using transport.resolve.

Example

The example below is based upon the PIO-1 broadcast presence API. Basically the PIO-1's send out a broadcast UDP packet every so often on port 5998. You can also request the PIO-1's to announce themselves. This is done by sending a specially crafted broadcast message to port 5999.

 

function callback( connection, data, address, port )

 print(data,address,port)

end

 

pioListener = transport.udp( function ( data, address, port )        

 callback(c, data, address, port)

end)

 

print(pioListener:listen( 5998 ))

 

bp = 'PIO-1\002'

pioListener:send(bp, '255.255.255.255', 5999)