Archive for the ‘Networking’ Category

D Sample

Sunday, April 20th, 2008

I’ve been wanting to play a little with the D Language for a bit, so I finally did. After a bit of a false start by downloading the more experimental D 2.0 branch, I fetched the most recent version of the more sensible seeming D 1.0 line of compilers.

As a little test, I wrote some code that connects to web servers (only running on port 80) and performs a HEAD request for the root page. It includes a number of D’s features, such as array slicing, exception handling, foreach loops, and its nice “auto” syntax for automatically figuring out variable types.

There really isn’t much to it, but here’s the code:

import std.stdio;
import std.cstream;
import std.socket;
 
void head(string host){
    writefln("Head of %s", host);
 
    ushort port = 80;
    InternetAddress addr;
    try{
        addr = new InternetAddress(host, port);
        writefln("%s", addr.toString());
    }catch(AddressException e){
        derr.writefln("Caught error: %s", e);
        return;
    }
 
    auto sock = new Socket(AddressFamily.INET, SocketType.STREAM);
    sock.connect(addr);
 
    sock.send("HEAD / HTTP/1.1\n");
    sock.send("Host: ");
    sock.send(host);
    sock.send("\n");
    sock.send("Connection: close\n");
    sock.send("\n");
 
    char[8] buf;        // buffer intentionally tiny
    int len;
    writefln("------------");
    while((len = sock.receive(buf)) != 0){
        writef("%s", buf[0..len]);
    }
    writefln("------------");
 
    sock.close();
}
 
int main(string args[]){
    if(args.length == 1){
        head("localhost");
        return 0;
    }
 
    foreach(argc, argv; args[1..args.length]){
        head(argv);
    }
    return 0;
}