D Lang Socket Programming Example
Ali Çehreli
acehreli at yahoo.com
Fri Sep 6 14:02:09 PDT 2013
On 09/06/2013 01:47 PM, Savsak wrote:
> Hi Friends,
>
> Socket programming with the D programming language is the most simple
> way how to do it
>
> For example, the sample with Tango, but not by phobos
>
> How do I do this with a simple, but phobos
>
>
> import tango.io.Stdout;
>
> import tango.net.Socket;
> import tango.net.ServerSocket;
> import tango.net.SocketConduit;
>
> int main() {
> Socket server = new Socket(AddressFamily.UNIX,
> SocketType.STREAM,
> ProtocolType.IP);
>
> while(true) {
> Socket client = server.accept();
>
> char[1024] buffer;
> client.receive(buffer);
>
> Stdout.format("The client said'{}'.", buffer);
>
> client.shutdown(SocketShutdown.BOTH);
> client.detach();
> }
> return 0;
> }
Here is a Phobos translation:
import std.stdio;
import std.socket;
void main() {
Socket server = new TcpSocket();
server.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR,
true);
server.bind(new InternetAddress(8080));
server.listen(1);
while(true) {
Socket client = server.accept();
char[1024] buffer;
auto received = client.receive(buffer);
writefln("The client said:\n%s", buffer[0.. received]);
enum header =
"HTTP/1.0 200 OK\nContent-Type: text/html; charset=utf-8\n\n";
string response = header ~ "Hello World!\n";
client.send(response);
client.shutdown(SocketShutdown.BOTH);
client.close();
}
}
Ali
P.S. Note that there is also the D.learn newsgroup.
P.P.S. This question came up on two separate Turkish D forums recently:
http://ddili.org/forum/post/10063
http://forum.ceviz.net/d-dili/127048-ddili-socket-okuma-veri-gonderme-quotnon-blocking-i-oquot.html
More information about the Digitalmars-d
mailing list