Creating a network client and server
Networking is a common requirement in modern applications. Phobos offers a module, std.socket
, which provides a foundation for networked applications. We'll write a client and server pair to demonstrate how to use it. The client will send lines from standard input to the server. The server will accept any number of connections, say hello to new clients, and then echo back whatever it received.
How to do it…
We'll be building two separate applications: the client and the server.
Client
Let's create a client by executing the following steps:
Create a
Socket
object.Connect to the server.
Declare a buffer to hold the received data. The buffer must be preallocated to the maximum amount of data you want to handle in a single call to receive the data. Here, we'll use a static array of length 1024; it will have plenty of room to hold our message.
Receive the hello message we sent in the server.
Then, send each line of the message to the server, wait for the response...