std.socket replacement
Max Freck via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 3 23:19:18 PDT 2016
On Sunday, 29 November 2015 at 18:00:34 UTC, tired_eyes wrote:
> On Sunday, 29 November 2015 at 16:10:22 UTC, Alex Parrill wrote:
>> std.stream, and the stream interface in general, is deprecated
>> in favor of ranges, which are more generic and flexible.
>
> Could you please give a small example?
> Consider this minimal app:
>
>
> import std.stdio;
> import std.socket;
> import std.socketstream;
>
> void main() {
> auto socket = new TcpSocket(new
> InternetAddress("dlang.org", 80));
> scope(exit) socket.close();
>
> auto ss = new SocketStream(socket);
> ss.writeString("GET http://dlang.org HTTP/1.1\r\n"
> "Host: dlang.org\r\n"
> "Connection: close\r\n"
> "\r\n");
>
> while (! ss.eof) {
> writeln(ss.readLine());
> }
> }
>
>
> How should it look with ranges instead of socketstream? I
> thought I understand ranges in general, but I can't figure out
> how they can be applied to this case.
In case someone is still looking for the answer, just like me. It
will be something like that:
import std.stdio;
import std.socket;
enum receiveBufferLength = 1024;
void main() {
auto socket = new TcpSocket(new InternetAddress("dlang.org",
80));
scope(exit) socket.close();
socket.send("GET http://dlang.org HTTP/1.1\r\nHost:
dlang.org\r\nConnection: close\r\n\r\n");
string response;
char[receiveBufferLength] receiveBuffer;
while (true) {
auto received = socket.receive(receiveBuffer[0 ..
receiveBufferLength]);
response ~= receiveBuffer[0 .. received];
if (received == 0) break;
}
write(response);
}
More information about the Digitalmars-d-learn
mailing list