Haskell Network Programming - UDP Client and Server

2017-06-12
haskellnetworking

Using the network package we can build a low level UDP server and client.

It is important to remember to use Datagram to receive data via UDP. Then we can bind the socket to the address and wait to receive data.

The client code is similar. We need to sned data via Datagram or the server will ignore it. Then we run sendAll with a ByteString and the server will receive the message.

We run the server in a separate thread because recv is blocking. We add a few threadDelays to make sure that the server has started up and that the prints from different threads do not occur at the same time. Otherwise, the messages might print at the same time and be illegible.

When main terminates all of the other threads in the program will terminate as well [2].

A real world UDP server will likely need to constantly receive requests. We can change the last line to use forever. It will repeatedly process incoming data.

References