Haskell Network Programming - TCP Client and Server

2017-06-12
haskellnetworking

Using the network package we can build a low level TCP server and client. We will make a simple echo server and client. The client sends a message, the server receives the message and sends the message back to the client, then the client receives the message it sent.

It is important to remember to use Stream to receive data and respond via TCP. Then we can bind the socket to the address, wait to receive data and then respond to the client.

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 TCP server will likely need to constantly receive requests and make responses. We can make the request/response code an infinite loop.

References