1 module dash.net.webconnection;
2 
3 import std.socket, std.bitmanip, std.stdio;
4 
5 enum ConnectionType : ushort
6 {
7 	TCP = 0x01,
8 	UDP = 0x02,
9 }
10 
11 immutable ubyte[] terminator = [ 0, 0, 0, 0 ];
12 
13 package abstract class WebConnection
14 {
15 	const ConnectionType type;
16 
17 	abstract shared void send( const ubyte[] args );
18 	shared bool recv( ref shared ubyte[] buf )
19 	{
20 		ubyte[] tempBuf = new ubyte[ 1024 ];
21 		buf.length = 0;
22 
23 		do
24 		{
25 			auto size = (cast(Socket)socket).receive( tempBuf );
26 
27 			if( size <= 0 )
28 				return false;
29 
30 			tempBuf.length = size;
31 
32 			buf ~= tempBuf;
33 		} while( cast(ubyte[])buf[ $-terminator.length..$ ] != terminator );
34 
35 
36 
37 		return true;
38 	}
39 	abstract shared void close();
40 
41 	Socket socket;
42 
43 protected:
44 	shared protected this( ConnectionType type )
45 	{
46 		this.type = type;
47 	}
48 }
49 
50 package class TCPConnection : WebConnection
51 {
52 	shared static TcpSocket listener;
53 
54 	shared this( string address, bool host )
55 	{
56 		super( ConnectionType.TCP );
57 
58 		if( host )
59 		{
60 			if( listener is null )
61 			{
62 				auto tmplistener = new TcpSocket;
63 				tmplistener.bind( new InternetAddress( 8080 ) );
64 				tmplistener.listen( 10 );
65 				listener = cast(shared)tmplistener;
66 			}
67 
68 			auto tmp = (cast()listener).accept();
69 			writeln( "TCP Connection accepted." );
70 			socket = cast(shared)tmp;
71 		}
72 		else
73 		{
74 			socket = cast(shared) new TcpSocket( new InternetAddress( address, 8080 ) );
75 		}
76 	}
77 
78 	shared static ~this()
79 	{
80 		if( listener )
81 			(cast()listener).close();
82 	}
83 
84 	override shared void send( const ubyte[] args )
85 	{
86 		auto sizeSent = (cast(Socket)socket).send( args ~ terminator );
87 
88 		assert( args.length + terminator.length == sizeSent, "Not all bytes sent." );
89 	}
90 
91 	override shared void close()
92 	{
93 		(cast(Socket)socket).close();
94 	}
95 }
96 
97 package class UDPConnection : WebConnection
98 {
99 	InternetAddress address;
100 
101 	shared this( string addr, bool host )
102 	{
103 		super( ConnectionType.UDP );
104 
105 		address = cast(shared) new InternetAddress( addr, 8080 );
106 		socket = cast(shared) new UdpSocket();
107 
108 		(cast(Socket)socket).bind( new InternetAddress( 8080 ) );
109 		(cast(Socket)socket).connect( cast(Address)address );
110 	}
111 
112 	override shared void send( const ubyte[] args )
113 	{
114 		auto sizeSent = (cast(Socket)socket).sendTo( args ~ terminator, cast(Address)address );
115 
116 		assert( args.length + terminator.length == sizeSent, "Not all bytes sent." );
117 	}
118 
119 	override shared void close()
120 	{
121 		(cast(Socket)socket).close();
122 	}
123 }