UDP Messaging
This article describes how to use UDP to create a simple chat program with HAC but first what is UDP?
UDP stands for User Datagram Protocol and is an easy way to send short messages because unlike TCP it does not expect an acknowledgment from the receiver. The message is sent to the target as a datagram which has just two parts, the sender’s address and the message content. UDP is often used in games and other time critical applications where the sender does not have time to wait for an acknowledgement from the receiving party. It is useful when the loss of a single message is not crucial although in practical terms message loss is very unlikely on local networks unless the network and/or the related devices are very busy.
UDP advantages are:-
- fire and forget with no need to check if received.
- fast as packets are much shorter.
UDP disadvantages are:-
- does not work on some phone networks as they block ports.
- for internet use it may not work if you or your target are behind a router.
A example of using UDP is when a master device must communicate with a number of slave devices such as in local network of a school or business. Another example is using a device to communicate with a microprocessor or other hardware device that supports UDP.
More information about UDP is given towards the end of this article and further details can also be found here:-
.
How to use UDP?
Using UDP is very simple, just create a socket and set some parameters. You need to know the device input address, target address and which ports to use. As HAC apps can have several sockets open at a time so most UDP commands/functions need a socket number.
The app has to create a socket and then attach this socket to a port on the device. Ports are like openings onto the computer that can both receive and send data. Ports can listen for incoming datagrams and trigger an event when one arrives.
The basic parts of using a UDP socket are:-
- Create a UDP socket that handles ports and events.
- Connect the socket to a port to enable listening and receiving.
- Send a message.
- Receive a message.
- Event Handling.
.
UDP Example Project
This example comes from the HAC UDP demo project which is included with the more recent versions of HAC installer. It is also available on our website along with a built Android app:- HAC Project Web Page
If you need to test your UDP app then a full featured but easy to use UDP tester can be downloaded fromĀ here:- Simple Tools UDP Test Tool
The UDP project described here has just two screens, the network setup screen and the chat screen.
The network setup screen in Fig 1 shows the device(host/local address) as 192.168.1.64 and the target/recipient as 192.168.1.71. Both the host and target are using port 5042.
.
A screen shot of the actual chat part of the app is shown below in Fig 2. The top field is where the user enters their message and the lower field is the log where both their text and that of their target appear.
.
1) UDP Socket Creation
A socket is used to connect with the port and trigger any UDP events. The UdpCreateFN function will try to create a socket and if successful will return a positive integer as the socket number, otherwise it will return 0.
Global sockNum Put UdpCreateFN into sockNum if sockNum<1 then Message 'Cannot create socket' endif
To delete a socket and free up its memory use the UdpDelete command.
.
2) UDP Binding to a Port
In order to send or receive messages a socket must be bound or connected to a port. Once a connection is made then the port will listen for incoming messages and transfer them to the socket so it can raise a UDP event. As well as a socket number, making a port connection also requires the expected maximum size of the message in bytes and a rest time specified in milliseconds. The maximum message size is used in creating a buffer for holding the message and details of acceptable sizes are given later on. The rest time is used to reduces the load on the device so that after a message is received the listener will rest before listening again. If the rest time is set to zero then no rest is allowed and the listener will work continuously.
In the code below the message size is set as 1024 bytes and the rest time as 1000mS.
The port number is obtained from field 2 and is 5042 as shown in Fig 2.
Global sockNum Local port Put field 2 into port UdpConnect(sockNum,port,1000,1024)
To stop listening but still keep the socket in memory use the UdpClose command.
.
3) UDP Sending a Message
Sending a message requires specifying the target address, the message and the encoding to use for the message.
In the code below field 1 is where the user enters their text and field 2 is the log window as shown in Fig 2. The target address is obtained from the network screen, in Fig 1, as when the Chat button is pressed it simply loads the value of field 1 into the global variable targetAddress.
The encoding is used to set the format of the message string and depends upon the message contents such as language used or whether it is binary. Both the sender and receiver should agree on the encoding used.
Global sockNum,targetAddress Local message Put field 1 into message Put 'Local ' after field 2 Append message onto field 2 UdpSend(sockNum,targetAddress,message,'UTF8')
.
4) UDP Receiving a Message
When a message is received by a port that is bound to a socket then that socket will trigger a UDP ‘Data Received’ event. In this event the app can process the message and make any necessary response.
The received datagram has two parts, the message, and the sender’s address. Assuming a datagram has been received then the following code would extract the data and address from the specified socket. The actual socket number can be found within the event as shown later.
Local data,address Put UdpRxDataFN(sock) into data Put UdpRxAddressFN(sock) into address
.
5) UDP Events
There are three types of UDP event in HAC apps, Data Received, Message Sent, and Error. Their integer values are 1,2 and 3 respectively.
When a UDP event occurs it triggers the UDP script. This script can be edited using the script editor and is located in the Specials section of the Editor.
Whenever a UDP event occurs then the event script should check to see:-
- Which socket raised the event.
- What the event is.
The following code shows how to handle a UDP event:-
Local sock,event,data,address Put UdpIndexFN into sock Put UdpEventFN into event if event=1 then @ Data Received Put UdpRxDataFN(sock) into data Put UdpRxAddress(sock) into address else if event=2 then @ Message sent else @ Error endif endif
Additonal Info
It is possible to create your own protocol by embedding commands inside the messages so that both receiver and sender can coordinate their responses. As the messages are just strings then a simple protocol might be as follows:-
- first 3 characters representing the command – eg 001
- the next 5 characters representing the port – eg 45000
- the rest of the message.
Note, on some platforms the UDP listener will hear its own messages but they can be filtered out by checking if the address of the incoming datagram matches that of the device address. An app can find its own address using the function InputAddressFN.
The maximum size of a datagram message is 65,508 bytes although some networks limit this to 8,192 bytes. If the message size exceeds the network limit then the message will be split into multiple datagram packets therefore if the maximum size is not known then 8192 bytes might be a safe size to use.
.
Summary
With UDP it is very easy to make a simple messaging system although how complex it becomes will depend upon your needs. Messages are sent to the target machine as a datagram that includes just the message and sender’s address so allowing simple chat systems to be built. The main drawback of UDP is that it has problemsĀ working on the internet where the computers are one of several connected behind a router or on mobile phone networks where mobile providers often block ports.
Despite UDP’s drawbacks it is very easy to set up a messaging system on a local network or send data to any device that understand UDP.
.
Members of HAC forums can download the latest trial version of HAC, see details here:- http://www.hypernextandroid.com/hnfiles/downloads.html