Something that I think would be nice is being able to treat a network
connection the same way we can work with files and stdin.

Is there a plan already in place for phobos? If no, I might have
something usable to get started.

I peered into std.stdio's source and hacked something up. My plan was
simple: open the network, then assign the FILE* to it to the File
struct.

This is just for Linux; I haven't done Windows code like this for a
long time and I don't remember how. But this might be a useful
starting point anyway, so I figure I'll share it.


What I'd ultimately like is something like this for all D platforms,
and an add-on facility for handling multiple connections, including
incoming connections. I actually have something for this too, but it
is incompatible with the File struct (and Linux only again).


=========
import std.stdio;
import std.string;

import std.conv;

version(linux):

import std.c.linux.linux;
import std.c.linux.socket;

alias std.c.linux.socket sock;
alias std.c.linux.linux linux;

enum int PF_INET = 2;
enum int AF_INET = PF_INET;

extern(C) FILE* fdopen(int, const(char)*);

File openNetwork(string host, ushort port) {
        hostent* h;
        sockaddr_in addr;

        h = gethostbyname(std.string.toStringz(host));
        if(h is null)
                throw new StdioException("gethostbyname");

        int s = socket(PF_INET, SOCK_STREAM, 0);
        if(s == -1)
                throw new StdioException("socket");

        scope(failure)
                close(s);

        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        std.c.string.memcpy(&addr.sin_addr.s_addr, h.h_addr, h.h_length);

        if(sock.connect(s, cast(sockaddr*) &addr, addr.sizeof) == -1)
                throw new StdioException("Connect failed");

        FILE* fp = fdopen(s, "w+".ptr);

        File f;

        auto imp = new File.Impl(fp, 1, host ~ ":" ~ to!string(port));

        f.p = imp;

        return f;
}
========

Reply via email to