Net.hx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package asys;
  2. import haxe.NoData;
  3. import haxe.async.*;
  4. import asys.net.*;
  5. import asys.net.SocketOptions.SocketConnectTcpOptions;
  6. import asys.net.SocketOptions.SocketConnectIpcOptions;
  7. import asys.net.Server.ServerOptions;
  8. import asys.net.Server.ServerListenTcpOptions;
  9. import asys.net.Server.ServerListenIpcOptions;
  10. enum SocketConnect {
  11. Tcp(options:SocketConnectTcpOptions);
  12. Ipc(options:SocketConnectIpcOptions);
  13. }
  14. enum ServerListen {
  15. Tcp(options:ServerListenTcpOptions);
  16. Ipc(options:ServerListenIpcOptions);
  17. }
  18. typedef SocketCreationOptions = SocketOptions & {?connect:SocketConnect};
  19. typedef ServerCreationOptions = ServerOptions & {?listen:ServerListen};
  20. /**
  21. Network utilities.
  22. **/
  23. class Net {
  24. /**
  25. Constructs a socket with the given `options`. If `options.connect` is
  26. given, an appropriate `connect` method is called on the socket. If `cb` is
  27. given, it is passed to the `connect` method, so it will be called once the
  28. socket successfully connects or an error occurs during connecting.
  29. The `options` object is given both to the `Socket` constructor and to the
  30. `connect` method.
  31. **/
  32. public static function createConnection(options:SocketCreationOptions, ?cb:Callback<NoData>):Socket {
  33. var socket = Socket.create(options);
  34. if (options.connect != null)
  35. switch (options.connect) {
  36. case Tcp(options):
  37. socket.connectTcp(options, cb);
  38. case Ipc(options):
  39. socket.connectIpc(options, cb);
  40. }
  41. return socket;
  42. }
  43. /**
  44. Constructs a server with the given `options`. If `options.listen` is
  45. given, an appropriate `listen` method is called on the server. If `cb` is
  46. given, it is passed to the `listen` method, so it will be called for each
  47. client that connects to the server.
  48. The `options` object is given both to the `Server` constructor and to the
  49. `listen` method.
  50. **/
  51. public static function createServer(?options:ServerCreationOptions, ?listener:Listener<Socket>):Server {
  52. var server = new Server(options);
  53. if (options.listen != null)
  54. switch (options.listen) {
  55. case Tcp(options):
  56. server.listenTcp(options, listener);
  57. case Ipc(options):
  58. server.listenIpc(options, listener);
  59. }
  60. return server;
  61. }
  62. }