Tomas
Tomas

Reputation: 33

Network Programming D language

I wanted to learn Network Programming, so I hit the net and started to research about it, I recently found this https://ruslanspivak.com/lsbaws-part1/ but it is in python, I am currently trying to convert it to D language, so the problem is that everytime I hit localhost:8888 on my browser it just don't return anything. Can you help me figure out what is wrong with it..

I just converted everything line by line from that code except the .receive and .send, which in D language needs to be ubyte, so I just placed a ubyte buffer in there.

import std.stdio;
import std.socket;


void main()
{

    ushort port = 8888;
    auto listener = new TcpSocket();
    writeln("Listening on port ", port);
    listener.blocking = false; 
    listener.bind(new InternetAddress(port));
    listener.listen(1);
    ubyte[] data = cast(ubyte[])"HTTP/1.1 200 OK

    <html><body>Test Works!!</body></html>";
    auto request = new ubyte[1024];
    while(true){
        listener.accept();
        listener.receive(request);
        listener.send(data);
        listener.close();
    }
}

Upvotes: 2

Views: 1036

Answers (1)

WebFreak001
WebFreak001

Reputation: 2533

You don't use the return value of listener.accept(), which is the client that connected to you. Also for me making it non-blocking crashed it at the start. Here is the fixed code where it works as expected:

import std.stdio;
import std.socket;

void main()
{

    ushort port = 3000;
    auto listener = new TcpSocket();
    writeln("Listening on port ", port);
    listener.blocking = true; 
    listener.bind(new InternetAddress(port));
    listener.listen(1);
    ubyte[] data = cast(ubyte[])"HTTP/1.1 200 OK

    <html><body>Test Works!!</body></html>";
    auto request = new ubyte[1024];
    while(true){
        auto client = listener.accept();
        client.receive(request);
        client.send(data);
        client.close();
    }
}

Upvotes: 7

Related Questions