ServerLoop.hx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /*
  2. * Copyright (C)2005-2012 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package neko.net;
  23. import sys.net.Socket;
  24. private typedef ServerClient<ClientData> = {
  25. var sock : Socket;
  26. var buffer : haxe.io.Bytes;
  27. var bufbytes : Int;
  28. var data : ClientData;
  29. }
  30. /**
  31. This class enables you to quickly create a custom server that can
  32. serve several clients in parallel. This server is using a single
  33. thread and process so the server itself processing is not parallel.
  34. Non-blocking sockets are used to ensure that a slow client does not
  35. block the others.
  36. **/
  37. class ServerLoop<ClientData> {
  38. /**
  39. Each client has an associated buffer. This is the initial buffer size which
  40. is set to 128 bytes by default.
  41. **/
  42. public static var DEFAULT_BUFSIZE = 128;
  43. /**
  44. Each client has an associated buffer. This is the maximum buffer size which
  45. is set to 64K by default. When that size is reached and some data can't be processed,
  46. the client is disconnected.
  47. **/
  48. public static var MAX_BUFSIZE = (1 << 16);
  49. /**
  50. This is the value of number client requests that the server socket
  51. listen for. By default this number is 10 but can be increased for
  52. servers supporting a large number of simultaneous requests.
  53. **/
  54. public var listenCount : Int;
  55. /**
  56. See [update].
  57. **/
  58. public var updateTime : Float;
  59. var newData : Socket -> ClientData;
  60. var socks : Array<Socket>;
  61. public var clients : List<ClientData>;
  62. /**
  63. Creates a server instance. The [newData] methods must return
  64. the data associated with the Client.
  65. **/
  66. public function new( ?newData ) {
  67. this.newData = if( newData == null ) function(_) { return null; } else newData;
  68. clients = new List();
  69. socks = new Array();
  70. listenCount = 10;
  71. updateTime = 1;
  72. }
  73. /**
  74. Closes the client connection and removes it from the client List.
  75. **/
  76. public function closeConnection( s : Socket ) : Bool {
  77. var cl : ServerClient<ClientData> = untyped s.__client;
  78. if( cl == null || !clients.remove(cl.data) )
  79. return false;
  80. socks.remove(s);
  81. try s.close() catch( e : Dynamic ) { };
  82. clientDisconnected(cl.data);
  83. return true;
  84. }
  85. /**
  86. The [update] method is called after each socket event has been
  87. processed or when [updateTime] has been reached. It can be used
  88. to perform time-regular tasks such as pings. By default [updateTime]
  89. is set to one second.
  90. **/
  91. public function update() {
  92. }
  93. /**
  94. This method is called after a client has been disconnected.
  95. **/
  96. public function clientDisconnected( d : ClientData ) {
  97. }
  98. /**
  99. This method can be used instead of writing directly to the socket.
  100. It ensures that all the data is correctly sent. If an error occurs
  101. while sending the data, no exception will occur but the client will
  102. be gracefully disconnected.
  103. **/
  104. public function clientWrite( s : Socket, buf : haxe.io.Bytes, pos : Int, len : Int ) {
  105. try {
  106. while( len > 0 ) {
  107. var nbytes = s.output.writeBytes(buf,pos,len);
  108. pos += nbytes;
  109. len -= nbytes;
  110. }
  111. } catch( e : Dynamic ) {
  112. closeConnection(s);
  113. }
  114. }
  115. /**
  116. This method is called when some data has been readed into a Client buffer.
  117. If the data can be handled, then you can return the number of bytes handled
  118. that needs to be removed from the buffer. It the data can't be handled (some
  119. part of the message is missing for example), returns 0.
  120. **/
  121. public function processClientData( d : ClientData, buf : haxe.io.Bytes, bufpos : Int, buflen : Int ) {
  122. throw "ServerLoop::processClientData is not implemented";
  123. return 0;
  124. }
  125. /**
  126. Called when an error occured. This enable you to log the error somewhere.
  127. By default the error is displayed using [trace].
  128. **/
  129. public function onError( e : Dynamic ) {
  130. trace(Std.string(e)+"\n"+haxe.CallStack.toString(haxe.CallStack.exceptionStack()));
  131. }
  132. function readData( cl : ServerClient<ClientData> ) {
  133. var buflen = cl.buffer.length;
  134. // eventually double the buffer size
  135. if( cl.bufbytes == buflen ) {
  136. var nsize = buflen * 2;
  137. if( nsize > MAX_BUFSIZE ) {
  138. if( buflen == MAX_BUFSIZE )
  139. throw "Max buffer size reached";
  140. nsize = MAX_BUFSIZE;
  141. }
  142. var buf2 = haxe.io.Bytes.alloc(nsize);
  143. buf2.blit(0,cl.buffer,0,buflen);
  144. buflen = nsize;
  145. cl.buffer = buf2;
  146. }
  147. // read the available data
  148. var nbytes = cl.sock.input.readBytes(cl.buffer,cl.bufbytes,buflen - cl.bufbytes);
  149. cl.bufbytes += nbytes;
  150. }
  151. function processData( cl : ServerClient<ClientData> ) {
  152. var pos = 0;
  153. while( cl.bufbytes > 0 ) {
  154. var nbytes = processClientData(cl.data,cl.buffer,pos,cl.bufbytes);
  155. if( nbytes == 0 )
  156. break;
  157. pos += nbytes;
  158. cl.bufbytes -= nbytes;
  159. }
  160. if( pos > 0 )
  161. cl.buffer.blit(0,cl.buffer,pos,cl.bufbytes);
  162. }
  163. /**
  164. Run the server. This function should never return.
  165. **/
  166. public function run( host : sys.net.Host, port : Int ) {
  167. var serv = new Socket();
  168. serv.bind(host,port);
  169. serv.listen(listenCount);
  170. socks = [serv];
  171. while( true ) {
  172. for( s in Socket.select(socks,null,null,updateTime).read ) {
  173. var cl : ServerClient<ClientData> = untyped s.__client;
  174. if( cl == null ) {
  175. // no associated client : it's our server socket
  176. var sock = serv.accept();
  177. sock.setBlocking(true);
  178. cl = {
  179. sock : sock,
  180. data : null,
  181. buffer : haxe.io.Bytes.alloc(DEFAULT_BUFSIZE),
  182. bufbytes : 0,
  183. };
  184. // bind the client
  185. untyped sock.__client = cl;
  186. // creates the data
  187. try {
  188. cl.data = newData(sock);
  189. } catch( e : Dynamic ) {
  190. onError(e);
  191. try sock.close() catch( e : Dynamic ) { };
  192. continue;
  193. }
  194. // adds the client to the lists
  195. socks.push(sock);
  196. clients.add(cl.data);
  197. } else {
  198. // read & process the data
  199. try {
  200. readData(cl);
  201. processData(cl);
  202. } catch( e : Dynamic ) {
  203. if( !Std.is(e,haxe.io.Eof) )
  204. onError(e);
  205. closeConnection(cl.sock);
  206. }
  207. }
  208. }
  209. update();
  210. }
  211. serv.close();
  212. }
  213. }