Socket.hx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 haxe.io.Error;
  24. import haxe.io.Bytes;
  25. import haxe.io.BytesData;
  26. import python.Exceptions;
  27. import python.Tuple;
  28. import python.lib.socket.Socket in PSocket;
  29. import python.lib.Socket in PSocketModule;
  30. import python.lib.socket.Address in PAddress;
  31. import python.lib.Select;
  32. private class SocketInput extends haxe.io.Input {
  33. var __s : PSocket;
  34. public function new(s) {
  35. __s = s;
  36. }
  37. public override function readByte() : Int {
  38. var r:BytesData;
  39. try {
  40. r = __s.recv(1,0);
  41. } catch( e : BlockingIOError ) {
  42. throw Blocked;
  43. }
  44. if( r.length == 0 )
  45. throw new haxe.io.Eof();
  46. return python.Syntax.pythonCode("r[0]");
  47. }
  48. public override function readBytes( buf : haxe.io.Bytes, pos : Int, len : Int ) : Int {
  49. var r;
  50. var data = buf.getData();
  51. try {
  52. r = __s.recv(len,0);
  53. for (i in pos...(pos+r.length)){
  54. data.set(i,r[i-pos]);
  55. }
  56. } catch( e : BlockingIOError ) {
  57. throw Blocked;
  58. }
  59. if( r.length == 0 )
  60. throw new haxe.io.Eof();
  61. return r.length;
  62. }
  63. public override function close() {
  64. super.close();
  65. if( __s != null ) __s.close();
  66. }
  67. }
  68. private class SocketOutput extends haxe.io.Output {
  69. var __s : PSocket;
  70. public function new(s) {
  71. __s = s;
  72. }
  73. public override function writeByte( c : Int ) {
  74. try {
  75. __s.send(python.Syntax.pythonCode('bytes([c])'),0);
  76. } catch( e : BlockingIOError ) {
  77. throw Blocked;
  78. }
  79. }
  80. public override function writeBytes( buf : haxe.io.Bytes, pos : Int, len : Int) : Int {
  81. try {
  82. var data = buf.getData();
  83. var payload = python.Syntax.pythonCode("data[{0}:{0}+{1}]", pos, len);
  84. var r = __s.send(payload,0);
  85. return r;
  86. } catch( e : BlockingIOError ) {
  87. throw Blocked;
  88. }
  89. }
  90. public override function close() {
  91. super.close();
  92. if( __s != null ) __s.close();
  93. }
  94. }
  95. /**
  96. 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.
  97. **/
  98. @:coreApi class Socket {
  99. var __s:PSocket;
  100. /**
  101. The stream on which you can read available data. By default the stream is blocking until the requested data is available,
  102. use `setBlocking(false)` or `setTimeout` to prevent infinite waiting.
  103. **/
  104. public var input(default,null) : haxe.io.Input;
  105. /**
  106. 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.
  107. **/
  108. public var output(default,null) : haxe.io.Output;
  109. /**
  110. A custom value that can be associated with the socket. Can be used to retrieve your custom infos after a `select`.
  111. ***/
  112. public var custom : Dynamic;
  113. /**
  114. Creates a new unconnected socket.
  115. **/
  116. public function new() : Void {
  117. }
  118. function __initSocket ():Void {
  119. __s = new PSocket();
  120. }
  121. function __init() : Void {
  122. __initSocket();
  123. input = new SocketInput(__s);
  124. output = new SocketOutput(__s);
  125. }
  126. /**
  127. Closes the socket : make sure to properly close all your sockets or you will crash when you run out of file descriptors.
  128. **/
  129. public function close() : Void {
  130. __s.close();
  131. }
  132. /**
  133. Read the whole data available on the socket.
  134. **/
  135. public function read() : String {
  136. return input.readAll().toString();
  137. }
  138. /**
  139. Write the whole data to the socket output.
  140. **/
  141. public function write( content : String ) : Void {
  142. output.writeString(content);
  143. }
  144. /**
  145. Connect to the given server host/port. Throw an exception in case we couldn't successfully connect.
  146. **/
  147. public function connect( host : Host, port : Int ) : Void {
  148. __init();
  149. var host_str = host.toString();
  150. __s.connect(Tuple2.make(host_str,port));
  151. }
  152. /**
  153. 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.
  154. **/
  155. public function listen( connections : Int ) : Void {
  156. __s.listen(connections);
  157. }
  158. /**
  159. Shutdown the socket, either for reading or writing.
  160. **/
  161. public function shutdown( read : Bool, write : Bool ) : Void
  162. __s.shutdown( (read && write) ? PSocketModule.SHUT_RDWR : read ? PSocketModule.SHUT_RD : PSocketModule.SHUT_WR );
  163. /**
  164. Bind the socket to the given host/port so it can afterwards listen for connections there.
  165. **/
  166. public function bind( host : Host, port : Int ) : Void {
  167. __init();
  168. var host_str = host.toString();
  169. __s.bind(Tuple2.make(host_str,port));
  170. }
  171. /**
  172. Accept a new connected client. This will return a connected socket on which you can read/write some data.
  173. **/
  174. public function accept() : Socket {
  175. var tp2:Tuple2<PSocket,PAddress> = __s.accept();
  176. var s = new Socket();
  177. s.__s = tp2._1;
  178. s.input = new SocketInput(s.__s);
  179. s.output = new SocketOutput(s.__s);
  180. return s;
  181. }
  182. /**
  183. Return the information about the other side of a connected socket.
  184. **/
  185. public function peer() : { host : Host, port : Int } {
  186. var pn = __s.getpeername();
  187. return { host:new Host( pn._1 ), port:pn._2}
  188. }
  189. /**
  190. Return the information about our side of a connected socket.
  191. **/
  192. public function host() : { host : Host, port : Int } {
  193. var pn = __s.getsockname();
  194. return { host:new Host( pn._1 ), port:pn._2};
  195. }
  196. /**
  197. Gives a timeout after which blocking socket operations (such as reading and writing) will abort and throw an exception.
  198. **/
  199. public function setTimeout( timeout : Float ) : Void {
  200. __s.settimeout(timeout);
  201. }
  202. /**
  203. Block until some data is available for read on the socket.
  204. **/
  205. public function waitForRead() : Void {
  206. }
  207. /**
  208. 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.
  209. **/
  210. public function setBlocking( b : Bool ) : Void {
  211. __s.setblocking(b);
  212. }
  213. /**
  214. 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.
  215. **/
  216. public function setFastSend( b : Bool ) : Void {}
  217. @:keep function fileno():Int return __s.fileno();
  218. /**
  219. Wait until one of the sockets groups is ready for the given operation :
  220. - `read` contains sockets on which we want to wait for available data to be read,
  221. - `write` contains sockets on which we want to wait until we are allowed to write some data to their output buffers,
  222. - `others` contains sockets on which we want to wait for exceptional conditions.
  223. - `select` will block until one of the condition is met, in which case it will return the sockets for which the condition was true.
  224. In case a `timeout` (in seconds) is specified, select might wait at worse until the timeout expires.
  225. **/
  226. public static function select(read : Array<Socket>, write : Array<Socket>, others : Array<Socket>, ?timeout : Float) : { read: Array<Socket>,write: Array<Socket>,others: Array<Socket> } {
  227. var t3 = Select.select(read,write,others,timeout);
  228. return {read:t3._1,write:t3._2,others:t3._3};
  229. }
  230. }