~lovesyao/+junk/transgs

« back to all changes in this revision

Viewing changes to nazo/socketstream.d

  • Committer: Nazo
  • Date: 2008-10-18 08:26:14 UTC
  • Revision ID: lovesyao@hotmail.com-20081018082614-22qgtg2gsotz5r2i
initial checkin

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/**
 
2
 * SocketStreamにforeachを拡張
 
3
 */
 
4
module nazo.socketstream;
 
5
import std.socketstream, std.socket, std.stream, std.stdio;
 
6
 
 
7
class SocketStream:std.socketstream.SocketStream{
 
8
  const uint buffsize=500;
 
9
  this(Socket sock,uint buffsize=buffsize.init){
 
10
    super(sock);
 
11
  }
 
12
  this(Socket sock,FileMode mode,uint buffsize=buffsize.init){
 
13
    super(sock,mode);
 
14
  }
 
15
  int opApply(int delegate(inout ubyte[] buff) dg){
 
16
    int result = 0;
 
17
    ubyte[] buf=new ubyte[buffsize];
 
18
    while((buf.length=read(buf))>0){
 
19
//      std.stdio.writefln(buf.length);
 
20
      result = dg(buf);
 
21
      if (result)
 
22
        break;
 
23
      buf.length=buffsize;
 
24
    }
 
25
    return result;
 
26
  }
 
27
}
 
28
 
 
29
import std.stdio, std.string;
 
30
 
 
31
unittest{
 
32
  auto ih=new InternetHost;
 
33
  ih.getHostByName("www.ietf.org");
 
34
  auto ia = new InternetAddress(ih.addrList[0], 80);
 
35
  auto tcp = new TcpSocket(ia.addressFamily());
 
36
  tcp.connect(ia);
 
37
  auto sock = new SocketStream(tcp);
 
38
  sock.write(cast(ubyte[])"GET /home.html\r\nAccept-Language: ja-jp,ja;q=0.8,en-us;q=0.5,en;q=0.3\r\n\r\n");
 
39
  ubyte[] data;
 
40
  foreach(ubyte[] buf;sock){
 
41
    data~=buf;
 
42
  }
 
43
  assert(find(cast(string)data,"<html")>=0);
 
44
  assert(find(cast(string)data,"</html>")>=0);
 
45
  sock.close();
 
46
}