Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Create a Socket object.

  2. Connect to the server.

  3. 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.

  4. Receive the hello message we sent in the server.

  5. Then, send each line of the message to the server, wait for the response...