Socket.hx 8.7 KB

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