Socket.hx 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 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. @:coreApi
  39. class Socket {
  40. private var sock:NativeSocket = null;
  41. public var input(default, null):haxe.io.Input;
  42. public var output(default, null):haxe.io.Output;
  43. public var custom:Dynamic;
  44. public function new():Void {
  45. sock = new NativeSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  46. sock.Blocking = true;
  47. }
  48. public function close():Void {
  49. sock.Close();
  50. input = null;
  51. output = null;
  52. }
  53. public function read():String {
  54. return input.readAll().toString();
  55. }
  56. public function write(content:String):Void {
  57. output.writeString(content);
  58. }
  59. public function connect(host:Host, port:Int):Void {
  60. sock.Connect(host.ipAddress, port);
  61. if (sock.Connected) {
  62. this.output = new cs.io.NativeOutput(new NetworkStream(sock));
  63. this.input = new cs.io.NativeInput(new NetworkStream(sock));
  64. } else {
  65. throw "Connection failed.";
  66. }
  67. }
  68. public function listen(connections:Int):Void {
  69. sock.Listen(connections);
  70. }
  71. public function shutdown(read:Bool, write:Bool):Void {
  72. if (read && write) {
  73. sock.Shutdown(SocketShutdown.Both);
  74. input = null;
  75. output = null;
  76. } else if (read) {
  77. sock.Shutdown(SocketShutdown.Receive);
  78. input = null;
  79. } else if (write) {
  80. sock.Shutdown(SocketShutdown.Send);
  81. output = null;
  82. }
  83. }
  84. public function bind(host:Host, port:Int):Void {
  85. sock = new NativeSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  86. sock.Bind(new IPEndPoint(host.ipAddress, port));
  87. }
  88. public function accept():Socket {
  89. var r = new Socket();
  90. r.sock = sock.Accept();
  91. r.output = new cs.io.NativeOutput(new NetworkStream(r.sock));
  92. r.input = new cs.io.NativeInput(new NetworkStream(r.sock));
  93. return r;
  94. }
  95. public function peer():{host:Host, port:Int} {
  96. var remoteIP = cast(sock.RemoteEndPoint, IPEndPoint);
  97. return {host: new Host(remoteIP.Address.ToString()), port: remoteIP.Port};
  98. }
  99. public function host():{host:Host, port:Int} {
  100. var localIP = cast(sock.LocalEndPoint, IPEndPoint);
  101. return {host: new Host(localIP.Address.ToString()), port: localIP.Port};
  102. }
  103. public function setTimeout(timeout:Float):Void {
  104. sock.ReceiveTimeout = sock.SendTimeout = Math.round(timeout * 1000);
  105. }
  106. public function waitForRead():Void {
  107. var end = Date.now().getTime() + ((sock.ReceiveTimeout <= 0) ? Math.POSITIVE_INFINITY : sock.ReceiveTimeout);
  108. while (sock.Available == 0 && Date.now().getTime() < end) {
  109. Thread.Sleep(5);
  110. }
  111. }
  112. public function setBlocking(b:Bool):Void {
  113. sock.Blocking = b;
  114. }
  115. public function setFastSend(b:Bool):Void {
  116. sock.NoDelay = b;
  117. }
  118. static public function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
  119. ?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
  120. var map:Map<Int, Socket> = new Map();
  121. inline function addSockets(sockets:Array<Socket>) {
  122. if (sockets != null)
  123. for (s in sockets)
  124. map[s.sock.Handle.ToInt32()] = s;
  125. }
  126. inline function getRaw(sockets:Array<Socket>):ArrayList {
  127. var a = new ArrayList(sockets == null ? 0 : sockets.length);
  128. if (sockets != null)
  129. for (s in sockets) {
  130. a.Add(s.sock);
  131. }
  132. return a;
  133. }
  134. inline function getOriginal(result:ArrayList) {
  135. var a:Array<Socket> = [];
  136. for (i in 0...result.Count) {
  137. var s:NativeSocket = result[i];
  138. a.push(map[s.Handle.ToInt32()]);
  139. }
  140. return a;
  141. }
  142. addSockets(read);
  143. addSockets(write);
  144. addSockets(others);
  145. // unwrap Sockets into native sockets
  146. var rawRead:ArrayList = getRaw(read),
  147. rawWrite:ArrayList = getRaw(write),
  148. rawOthers:ArrayList = getRaw(others);
  149. var microsec = timeout == null ? -1 : Std.int(timeout * 1000000);
  150. NativeSocket.Select(rawRead, rawWrite, rawOthers, microsec);
  151. // convert native sockets back to Socket objects
  152. return {
  153. read: getOriginal(rawRead),
  154. write: getOriginal(rawWrite),
  155. others: getOriginal(rawOthers),
  156. }
  157. }
  158. }