Socket.hx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 cs.NativeArray;
  24. import cs.system.collections.ArrayList;
  25. import cs.system.net.IPEndPoint;
  26. import cs.system.net.sockets.AddressFamily;
  27. import cs.system.net.sockets.NetworkStream;
  28. import cs.system.net.sockets.ProtocolType;
  29. import cs.system.net.sockets.SocketFlags;
  30. import cs.system.net.sockets.SocketShutdown;
  31. import cs.system.net.sockets.SocketType;
  32. import cs.system.threading.Thread;
  33. import cs.system.net.sockets.Socket in NativeSocket;
  34. import haxe.io.Bytes;
  35. import haxe.io.Error;
  36. import haxe.io.Input;
  37. import haxe.io.Output;
  38. /**
  39. 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.
  40. **/
  41. @:coreapi
  42. class Socket {
  43. private var sock : NativeSocket = null;
  44. /**
  45. The stream on which you can read available data. By default the stream is blocking until the requested data is available,
  46. use `setBlocking(false)` or `setTimeout` to prevent infinite waiting.
  47. **/
  48. public var input(default,null) : haxe.io.Input;
  49. /**
  50. 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.
  51. **/
  52. public var output(default,null) : haxe.io.Output;
  53. /**
  54. A custom value that can be associated with the socket. Can be used to retrieve your custom infos after a `select`.
  55. ***/
  56. public var custom : Dynamic;
  57. /**
  58. Creates a new unconnected socket.
  59. **/
  60. public function new() : Void {
  61. sock = new NativeSocket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
  62. sock.Blocking = true;
  63. }
  64. /**
  65. Closes the socket : make sure to properly close all your sockets or you will crash when you run out of file descriptors.
  66. **/
  67. public function close() : Void {
  68. sock.Close();
  69. input = null;
  70. output = null;
  71. }
  72. /**
  73. Read the whole data available on the socket.
  74. **/
  75. public function read() : String {
  76. return input.readAll().toString();
  77. }
  78. /**
  79. Write the whole data to the socket output.
  80. **/
  81. public function write( content : String ) : Void {
  82. output.writeString( content );
  83. }
  84. /**
  85. Connect to the given server host/port. Throw an exception in case we couldn't successfully connect.
  86. **/
  87. public function connect( host : Host, port : Int ) : Void {
  88. sock.Connect( host.ipAddress, port );
  89. if (sock.Connected) {
  90. this.output = new cs.io.NativeOutput( new NetworkStream(sock) );
  91. this.input = new cs.io.NativeInput( new NetworkStream(sock) );
  92. } else {
  93. throw "Connection failed.";
  94. }
  95. }
  96. /**
  97. 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.
  98. **/
  99. public function listen( connections : Int ) : Void {
  100. sock.Listen( connections );
  101. }
  102. /**
  103. Shutdown the socket, either for reading or writing.
  104. **/
  105. public function shutdown( read : Bool, write : Bool ) : Void {
  106. if ( read && write ) {
  107. sock.Shutdown( SocketShutdown.Both );
  108. input = null;
  109. output = null;
  110. } else if ( read ) {
  111. sock.Shutdown( SocketShutdown.Receive );
  112. input = null;
  113. } else if ( write ) {
  114. sock.Shutdown( SocketShutdown.Send );
  115. output = null;
  116. }
  117. }
  118. /**
  119. Bind the socket to the given host/port so it can afterwards listen for connections there.
  120. **/
  121. public function bind( host : Host, port : Int ) : Void {
  122. sock = new NativeSocket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
  123. sock.Bind( new IPEndPoint(host.ipAddress, port) );
  124. }
  125. /**
  126. Accept a new connected client. This will return a connected socket on which you can read/write some data.
  127. **/
  128. public function accept() : Socket {
  129. var r = new Socket();
  130. r.sock = sock.Accept();
  131. r.output = new cs.io.NativeOutput( new NetworkStream(r.sock) );
  132. r.input = new cs.io.NativeInput( new NetworkStream(r.sock) );
  133. return r;
  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 remoteIP = cast(sock.RemoteEndPoint, IPEndPoint);
  140. return { host: new Host(remoteIP.Address.ToString()), port: remoteIP.Port };
  141. }
  142. /**
  143. Return the information about our side of a connected socket.
  144. **/
  145. public function host() : { host : Host, port : Int } {
  146. var localIP = cast(sock.LocalEndPoint, IPEndPoint);
  147. return { host: new Host(localIP.Address.ToString()), port: localIP.Port };
  148. }
  149. /**
  150. Gives a timeout after which blocking socket operations (such as reading and writing) will abort and throw an exception.
  151. **/
  152. public function setTimeout( timeout : Float ) : Void {
  153. sock.ReceiveTimeout = sock.SendTimeout = Math.round(timeout * 1000);
  154. }
  155. /**
  156. Block until some data is available for read on the socket.
  157. **/
  158. public function waitForRead() : Void {
  159. var end = Date.now().getTime() + ((sock.ReceiveTimeout <= 0) ? Math.POSITIVE_INFINITY : sock.ReceiveTimeout);
  160. while ( sock.Available == 0 && Date.now().getTime() < end) {
  161. Thread.Sleep(5);
  162. }
  163. }
  164. /**
  165. 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.
  166. **/
  167. public function setBlocking( b : Bool ) : Void {
  168. sock.Blocking = b;
  169. }
  170. /**
  171. 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.
  172. **/
  173. public function setFastSend( b : Bool ) : Void {
  174. sock.NoDelay = b;
  175. }
  176. /**
  177. Wait until one of the sockets groups is ready for the given operation :
  178. * `read` contains sockets on which we want to wait for available data to be read,
  179. * `write` contains sockets on which we want to wait until we are allowed to write some data to their output buffers,
  180. * `others` contains sockets on which we want to wait for exceptional conditions.
  181. * `select` will block until one of the condition is met, in which case it will return the sockets for which the condition was true.
  182. In case a `timeout` (in seconds) is specified, select might wait at worse until the timeout expires.
  183. **/
  184. static public function select(read : Array<Socket>, write : Array<Socket>, others : Array<Socket>, ?timeout : Float) : { read: Array<Socket>,write: Array<Socket>,others: Array<Socket> } {
  185. var map:Map<Int, Socket> = new Map();
  186. inline function addSockets(sockets:Array<Socket>) {
  187. if (sockets != null) for (s in sockets) map[s.sock.Handle.ToInt32()] = s;
  188. }
  189. inline function getRaw(sockets:Array<Socket>):ArrayList {
  190. var a = new ArrayList(sockets == null ? 0 : sockets.length);
  191. if (sockets != null) for (s in sockets) {
  192. a.Add(s.sock);
  193. }
  194. return a;
  195. }
  196. inline function getOriginal(result:ArrayList) {
  197. var a:Array<Socket> = [];
  198. for (i in 0 ... result.Count) {
  199. var s:NativeSocket = result[i];
  200. a.push(map[s.Handle.ToInt32()]);
  201. }
  202. return a;
  203. }
  204. addSockets(read);
  205. addSockets(write);
  206. addSockets(others);
  207. // unwrap Sockets into native sockets
  208. var rawRead:ArrayList = getRaw(read),
  209. rawWrite:ArrayList = getRaw(write),
  210. rawOthers:ArrayList = getRaw(others);
  211. var microsec = timeout == null ? -1 : Std.int(timeout * 1000000);
  212. NativeSocket.Select(rawRead, rawWrite, rawOthers, microsec);
  213. // convert native sockets back to Socket objects
  214. return {
  215. read: getOriginal(rawRead),
  216. write: getOriginal(rawWrite),
  217. others: getOriginal(rawOthers),
  218. }
  219. }
  220. }