Socket.hx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * Copyright (C)2005-2018 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 sys.net;
  23. import lua.lib.luasocket.Socket as LuaSocket;
  24. import lua.lib.luasocket.socket.*;
  25. import lua.*;
  26. import haxe.io.Bytes;
  27. /**
  28. A TCP socket class : allow you to both connect to a given server and exchange messages or start your own server and wait for connections.
  29. **/
  30. class Socket {
  31. /**
  32. The stream on which you can read available data. By default the stream is blocking until the requested data is available,
  33. use `setBlocking(false)` or `setTimeout` to prevent infinite waiting.
  34. **/
  35. public var input(default,null) : haxe.io.Input;
  36. /**
  37. The stream on which you can send data. Please note that in case the output buffer you will block while writing the data, use `setBlocking(false)` or `setTimeout` to prevent that.
  38. **/
  39. public var output(default,null) : haxe.io.Output;
  40. /**
  41. A custom value that can be associated with the socket. Can be used to retrieve your custom infos after a `select`.
  42. ***/
  43. var custom : Dynamic;
  44. /**
  45. A Lua specific datatype for a tcp server instance
  46. **/
  47. var _socket : LuaSocket;
  48. var blocking = false;
  49. /**
  50. Creates a new unconnected socket.
  51. **/
  52. public function new() : Void { }
  53. /**
  54. Closes the socket : make sure to properly close all your sockets or you will crash when you run out of file descriptors.
  55. **/
  56. public function close() : Void {
  57. _socket.close();
  58. }
  59. /**
  60. Read the whole data available on the socket.
  61. **/
  62. public function read() : String {
  63. return input.readAll().toString();
  64. }
  65. /**
  66. Write the whole data to the socket output.
  67. **/
  68. public function write( content : String ) : Void {
  69. output.writeString(content);
  70. }
  71. /**
  72. Connect to the given server host/port. Throw an exception in case we couldn't successfully connect.
  73. **/
  74. public function connect( host : Host, port : Int ) : Void {
  75. var res = LuaSocket.connect(host.host, port);
  76. if (res.message != null) throw 'Socket Error : ${res.message}';
  77. input = new SocketInput(res.result);
  78. output = new SocketOutput(res.result);
  79. _socket = res.result;
  80. }
  81. /**
  82. Allow the socket to listen for incoming questions. The parameter tells how many pending connections we can have until they get refused. Use `accept()` to accept incoming connections.
  83. **/
  84. public function listen( connections : Int ) : Void {
  85. var res = LuaSocket.tcp();
  86. if (res.message != null) throw 'Socket Listen Error : ${res.message}';
  87. res.result.listen(connections);
  88. _socket = res.result;
  89. }
  90. /**
  91. Shutdown the socket, either for reading or writing.
  92. **/
  93. public function shutdown( read : Bool, write : Bool ) : Void {
  94. var client : TcpClient = cast _socket;
  95. switch [read, write] {
  96. case [true ,true] : client.shutdown(Both);
  97. case [true ,false] : client.shutdown(Receive);
  98. case [false ,true] : client.shutdown(Send);
  99. default : null;
  100. }
  101. }
  102. /**
  103. Bind the socket to the given host/port so it can afterwards listen for connections there.
  104. **/
  105. public function bind( host : Host, port : Int ) : Void {
  106. var res = LuaSocket.bind(host.host, port);
  107. if (res.message != null) throw 'Socket Bind Error : ${res.message}';
  108. _socket = res.result;
  109. }
  110. /**
  111. Accept a new connected client. This will return a connected socket on which you can read/write some data.
  112. **/
  113. public function accept() : Socket {
  114. var server : TcpServer = cast _socket;
  115. var res = server.accept();
  116. if (res.message != null) throw 'Error : ${res.message}';
  117. var sock = new Socket();
  118. sock._socket = res.result;
  119. sock.input = new SocketInput(res.result);
  120. sock.output = new SocketOutput(res.result);
  121. return sock;
  122. }
  123. /**
  124. Return the information about the other side of a connected socket.
  125. **/
  126. public function peer() : { host : Host, port : Int } {
  127. var client : TcpClient = cast _socket;
  128. var res = client.getpeername();
  129. var host = new Host(res.address);
  130. return { host : host, port : Std.parseInt(res.port)};
  131. }
  132. /**
  133. Return the information about our side of a connected socket.
  134. **/
  135. public function host() : { host : Host, port : Int } {
  136. var server : TcpServer = cast _socket;
  137. var res = server.getsockname();
  138. var host = new Host(res.address);
  139. return {host : host, port : Std.parseInt(res.port)};
  140. }
  141. /**
  142. Gives a timeout after which blocking socket operations (such as reading and writing) will abort and throw an exception.
  143. **/
  144. public inline function setTimeout( timeout : Float ) : Void {
  145. var client : TcpClient = cast _socket;
  146. client.settimeout(timeout);
  147. }
  148. /**
  149. Block until some data is available for read on the socket.
  150. **/
  151. public function waitForRead() : Void {
  152. select([this], null, null);
  153. }
  154. /**
  155. Change the blocking mode of the socket. A blocking socket is the default behavior. A non-blocking socket will abort blocking operations immediately by throwing a haxe.io.Error.Blocked value.
  156. **/
  157. public function setBlocking( b : Bool ) : Void {
  158. blocking = b;
  159. }
  160. /**
  161. Allows the socket to immediately send the data when written to its output : this will cause less ping but might increase the number of packets / data size, especially when doing a lot of small writes.
  162. **/
  163. public function setFastSend( b : Bool ) : Void {
  164. var client : TcpClient = cast _socket;
  165. client.setoption(TcpNoDelay, true);
  166. }
  167. /**
  168. Wait until one of the sockets groups is ready for the given operation :
  169. - `read`contains sockets on which we want to wait for available data to be read,
  170. - `write` contains sockets on which we want to wait until we are allowed to write some data to their output buffers,
  171. - `others` contains sockets on which we want to wait for exceptional conditions.
  172. - `select` will block until one of the condition is met, in which case it will return the sockets for which the condition was true.
  173. In case a `timeout` (in seconds) is specified, select might wait at worse until the timeout expires.
  174. **/
  175. static public function select(read : Array<Socket>, write : Array<Socket>, others : Array<Socket>, ?timeout : Float) : { read: Array<Socket>, write: Array<Socket>, others: Array<Socket> } {
  176. var read_tbl = read == null ? Table.create() : Table.fromArray([for (r in read) cast r._socket]);
  177. var write_tbl = write == null ? Table.create() : Table.fromArray(([for (r in write) cast r._socket]));
  178. var res = LuaSocket.select(read_tbl, write_tbl, timeout);
  179. var convert_socket = function(x : LuaSocket){
  180. var sock = new Socket();
  181. sock.input = new SocketInput(cast x);
  182. sock.output = new SocketOutput(cast x);
  183. return sock;
  184. }
  185. var read_arr = res.read == null ? [] : lua.Lib.tableToArray(res.read).map(convert_socket);
  186. var write_arr = res.write == null ? [] : lua.Lib.tableToArray(res.write).map(convert_socket);
  187. return {read : read_arr, write : write_arr, others : []};
  188. }
  189. }
  190. private class SocketInput extends haxe.io.Input {
  191. var s : TcpClient;
  192. public function new(s : TcpClient) {
  193. this.s = s;
  194. }
  195. override public function readByte() : Int {
  196. var res = s.receive(1);
  197. if (res.message == "closed") throw new haxe.io.Eof();
  198. else if (res.message != null) throw 'Error : ${res.message}';
  199. return res.result.charCodeAt(0);
  200. }
  201. override public function readBytes( s : Bytes, pos : Int, len : Int ) : Int {
  202. var k = len;
  203. var b = s.getData();
  204. if( pos < 0 || len < 0 || pos + len > s.length )
  205. throw haxe.io.Error.OutsideBounds;
  206. try{
  207. while( k > 0 ) {
  208. b[pos] = cast readByte();
  209. pos++;
  210. k--;
  211. }
  212. } catch(e:haxe.io.Eof){
  213. if (pos == 0){
  214. throw e;
  215. }
  216. }
  217. return len-k;
  218. }
  219. }
  220. private class SocketOutput extends haxe.io.Output {
  221. var s : TcpClient;
  222. public function new(s : TcpClient) {
  223. this.s = s;
  224. }
  225. override public function writeByte(c : Int ) : Void {
  226. s.send(String.fromCharCode(c));
  227. }
  228. }