Socket.hx 9.2 KB

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