Esempio n. 1
0
    public WebSocketService(SignalBus signalBus, MainThreadQueue mainThreadQueue, URLReader urlReader)
    {
        Debug.Log("WebSocketService ahoy!");
        _signalBus       = signalBus;
        _mainThreadQueue = mainThreadQueue;

        var browerUri = new UriBuilder(urlReader.ReadURL());
        var baseUri   = new UriBuilder(WEBSOCKET_PROTOCOL, browerUri.Host, browerUri.Port, browerUri.Path).Uri;
        var fullUri   = new Uri(baseUri, WEBSOCKET_URL_PATH);

        Debug.Log("Trying to connect to " + fullUri);

        var url = fullUri.ToString();

        //uncomment following line to connect to the deployed server
        //url = "ws://ggj.sqeezy.tech/socket";

        _webSocket = WebSocketFactory.CreateInstance(url);

        _webSocket.OnOpen    += OnOpen;
        _webSocket.OnMessage += OnMessage;
        _webSocket.OnError   += OnError;
        _webSocket.OnClose   += OnClose;

        _signalBus.Subscribe <NetworkEvent>(m => Send(m.ToJson()));

        Connect();
    }
        public BrokerConnection(string uri, string realm)
        {
            WebSocketFactory.Init(() => new ClientWebSocketConnection());

            _channel = new WampChannelFactory()
                       .ConnectToRealm(realm)
                       .WebSocketTransport(uri)
                       .JsonSerialization()
                       .Build();

            Func <Task> connect = async() =>
            {
                Log.Information("Trying to connect to broker {brokerUri}", uri);

                try
                {
                    await _channel.Open();

                    Log.Debug("Connection Opened.");

                    _subject.OnNext(Connected.Yes(new Broker(_channel)));
                }
                catch (Exception exception)
                {
                    Log.Error(exception, "Connection Failed.");

                    _subject.OnNext(Connected.No <IBroker>());
                    throw exception;
                }
            };

            _reconnector = new WampChannelReconnector(_channel, connect);
        }
Esempio n. 3
0
        static void Main()
        {
            UserManager.Init();
            WebSocketFactory.Init(() => new WebSocketConnection());
            if (int.TryParse(ConfigurationManager.AppSettings["InsecureServerPort"], out int insecurePort))
            {
                var insecureServer = new WebSocketServer(insecurePort);
                insecureServer.AddWebSocketService <Connection>("/");
                insecureServer.KeepClean = false;
                insecureServer.Start();
            }
            if (int.TryParse(ConfigurationManager.AppSettings["SecureServerPort"], out int securePort))
            {
                var server = new WebSocketServer(securePort, true)
                {
                    SslConfiguration = { ServerCertificate = new X509Certificate2(ConfigurationManager.AppSettings["CertificateFile"], ConfigurationManager.AppSettings["CertificatePassword"]) }
                };
                server.AddWebSocketService <Connection>("/");
                server.KeepClean = false;
                server.Start();
            }
            var kill = new ManualResetEvent(false);

            Console.CancelKeyPress += delegate { kill.Set(); };
            kill.WaitOne();
        }
 /// <summary>
 /// LeanCluod .NET Realtime SDK 内置默认的 WebSocketClient
 /// 开发者可以在初始化的时候指定自定义的 WebSocketClient
 /// </summary>
 public DefaultWebSocketClient()
 {
     connection            = WebSocketFactory.Create();
     connection.OnOpened  += Connection_OnOpened;
     connection.OnMessage += Connection_OnMessage;
     connection.OnClosed  += Connection_OnClosed;
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            // create the server
            var nugget = new WebSocketServer("ws://localhost:8181", null);

            var factory = new WebSocketFactory(nugget);

            // register the handler
            factory.Register <PostSocket>("/subsample");
            // register the model factory
            // this is important since we need the model factory to create the models
            // the string passed is the name of the sub protocol that the factory should be used for
            // any client connecting with this subprotocol, will have all its data send throught the factory
            //nugget.SetSubProtocolModelFactory(new PostFactory(), "post");

            // start the server
            nugget.Start();
            // info
            Console.WriteLine("Server started, open client.html in a websocket-enabled browser");

            // keep alive
            var input = Console.ReadLine();

            while (input != "exit")
            {
                input = Console.ReadLine();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Connects to server then dends XML data
        /// </summary>
        public static void Send(XElement body)
        {
            if (!_endPointSet)
            {
                throw new Exception(
                          "Ip and port wasn't set. Call AccountsTransport.SetIpEndpoint method before sending any data.");
            }

            //Create and set up a new socket
            mySocket = WebSocketFactory.CreateInstance("ws://" + _accountsServerIp + ":" + _accountsServerPort);

            // buffer message
            _bufferedMessages.Enqueue(body);

            // not connected (first message)
            if (!IsConnected && !IsConnecting)
            {
                //Connect(); <- method was removed to make clear meaning of a 'SendBuferedMessages' method and 'IsConnecting' bool

                IsConnecting = true;

                //Init callbacks
                mySocket.OnOpen    += SendBuferedMessages;
                mySocket.OnMessage += OnMessage;
                mySocket.OnError   += OnError;
                mySocket.OnClose   += OnClose;

                //Connect
                mySocket.Connect();
            }
            else // if already connected
            {
                SendBuferedMessages();
            }
        }
        public WebSocketClient()
        {
            WebsocketConnection.Link();
            connection = WebSocketFactory.Create();

            ClientWebSocket cws = new ClientWebSocket();
        }
Esempio n. 8
0
    public void WSConnect()
    {
        // Create WebSocket instance
        ws = WebSocketFactory.CreateInstance(socket_adress);

        // Add OnOpen event listener
        ws.OnOpen += () =>
        {
            Debug.Log("WS connected!");
            Debug.Log("WS state: " + ws.GetState().ToString());
            //ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!"));
        };

        // Add OnMessage event listener
        weOnMessage();

        // Add OnError event listener
        ws.OnError += (string errMsg) =>
        {
            Debug.Log("WS error: " + errMsg);
            //ws.Close();
        };


        // Add OnClose event listener
        ws.OnClose += (WebSocketCloseCode code) =>
        {
            Debug.Log("WS closed with code: " + code.ToString());
            cnntStat = 1;
        };


        // Connect to the server
        ws.Connect();
    }
Esempio n. 9
0
 protected GameService()
 {
     _webSocket            = WebSocketFactory.Create();
     _webSocket.OnOpened  += WebSocket_OnOpened;
     _webSocket.OnClosed  += WebSocket_OnClosed;
     _webSocket.OnMessage += WebSocket_OnMessage;
     _webSocket.OnError   += WebSocket_OnError;
 }
Esempio n. 10
0
 public WebSocket()
 {
     connection            = WebSocketFactory.Create();
     connection.OnOpened  += OnOpened;
     connection.OnClosed  += OnClosed;
     connection.OnError   += OnError;
     connection.OnMessage += OnMessage;
 }
Esempio n. 11
0
 public DevicesPage()
 {
     InitializeComponent();
     Title             = L10n.Localize("DevicesTitle");
     str               = new StateActionResources();
     devicesCollection = new ObservableCollection <Plug>();
     connection        = WebSocketFactory.Create();
 }
        public MainPage()
        {
            InitializeComponent();

            webSocketConn = WebSocketFactory.Create();

            webSocketConn.OnMessage += WebSocketConn_OnMessage;
        }
Esempio n. 13
0
 public ChitChatPage()
 {
     InitializeComponent();
     _connection            = WebSocketFactory.Create();
     _connection.OnOpened  += Connection_OnOpened;
     _connection.OnMessage += Connection_OnMessage;
     _connection.OnClosed  += Connection_OnClosed;
     _connection.OnError   += Connection_OnError;
 }
Esempio n. 14
0
 public TestBroker()
 {
     WebSocketFactory.Init(() => new ClientWebSocketConnection());
     _channel = new WampChannelFactory()
                .ConnectToRealm("com.weareadaptive.reactivetrader")
                .WebSocketTransport(TestAddress.Broker)
                .JsonSerialization()
                .Build();
 }
        public static IWebSocketTransportSyntax WebSocketTransport(
            this ChannelFactorySyntax.IRealmSyntax realmSyntax, WebSocketFactory webSocketFactory, Uri address)
        {
            WebSocketActivator connectionActivator = new WebSocketActivator(address)
            {
                WebSocketFactory = webSocketFactory
            };

            return(GetWebSocketTransportSyntax(realmSyntax, connectionActivator));
        }
Esempio n. 16
0
        public MainViewModel()
        {
            _hostAddressSubject   = new BehaviorSubject <int>(0);
            _connection           = WebSocketFactory.Create();
            _connection.OnOpened += () => ConnectionState = ConnectionState.Connected();

            InitProperties();
            InitCachingOfIpAddress();
            HandleOpenSocketConnection();
        }
Esempio n. 17
0
        public MainPage()
        {
            InitializeComponent();

            // Get a websocket from your PCL library via the factory
            _connection            = WebSocketFactory.Create();
            _connection.OnOpened  += Connection_OnOpened;
            _connection.OnMessage += Connection_OnMessage;
            _connection.OnClosed  += Connection_OnClosed;
            _connection.OnError   += Connection_OnError;
        }
Esempio n. 18
0
        protected ASocket(Type typeMarker)
        {
            _messageQueue = new List <IModelSend>();
            TypeMarker    = typeMarker;
            _websocket    = WebSocketFactory.Create();

            _websocket.OnMessage += OnMessageReceive;
            _websocket.OnOpened  += OnOpened;
            _websocket.OnClosed  += OnClosed;
            _websocket.OnError   += OnError;
        }
Esempio n. 19
0
        public WebSocketPOCPage()
        {
            InitializeComponent();

            _connection            = WebSocketFactory.Create();
            _connection.OnOpened  += Connection_OnOpened;
            _connection.OnMessage += Connection_OnMessage;
            _connection.OnClosed  += Connection_OnClosed;
            _connection.OnError   += Connection_OnError;
            Debug.WriteLine("In constructor");
        }
Esempio n. 20
0
        public void Connect(string endpoint)
        {
            connection            = WebSocketFactory.Create();
            connection.OnOpened  += Connection_OnOpened;
            connection.OnClosed  += Connection_OnClosed;
            connection.OnMessage += Connection_OnMessage;
            connection.OnError   += Connection_OnError;
            connection.OnLog     += Connection_OnLog;

            connection.Open(endpoint);
        }
Esempio n. 21
0
        public static WebSocketPair Create()
        {
            // Create streams
            var serverStream = new DuplexStream();
            var clientStream = serverStream.CreateReverseDuplexStream();

            return(new WebSocketPair(
                       serverStream,
                       clientStream,
                       clientSocket: WebSocketFactory.CreateClientWebSocket(clientStream, null, TimeSpan.FromMinutes(2), 1024),
                       serverSocket: WebSocketFactory.CreateServerWebSocket(serverStream, null, TimeSpan.FromMinutes(2), 1024)));
        }
Esempio n. 22
0
    private void RegisterWebSocketEvents()
    {
        //Load the settings file from the webserver telling us which server we should be connecting to right now
        XmlDocument ServerSettingsDocument = new XmlDocument();

        ServerSettingsDocument.Load("http://swaelo.com/files/ClientServerSettings.xml");
        string UseTestServer = ServerSettingsDocument.DocumentElement.SelectSingleNode("/root/UseTestServer").InnerText;

        //Load the connection settings file as a text asset, then convert it to an XML document, then read the values from it
        TextAsset   ConnectionsFile     = (TextAsset)Resources.Load("ServerConnectionSettings");
        XmlDocument ConnectionsDocument = new XmlDocument();

        ConnectionsDocument.LoadXml(ConnectionsFile.text);

        //Load the test and release server IP values from the connection settings resource file
        string TestServerIP    = ConnectionsDocument.DocumentElement.SelectSingleNode("/root/TestServerIP").InnerText;
        string ReleaseServerIP = ConnectionsDocument.DocumentElement.SelectSingleNode("/root/ReleaseServerIP").InnerText;

        //Select the IP we were set to use based on the settings file stored on the web server
        string ServerIP = UseTestServer == "0" ? TestServerIP : ReleaseServerIP;

        Debug.Log("Connecting to '" + ServerIP + "'");
        ServerConnection = WebSocketFactory.CreateInstance(ServerIP);

        //Register new connection opened event
        ServerConnection.OnOpen += () =>
        {
            TryingToConnect       = false;
            ConnectionEstablished = true;
        };

        //Register message received event
        ServerConnection.OnMessage += (byte[] Message) =>
        {
            MessageReceived = true;
            ServerMessage   = Message;
        };

        //Register connection error event
        ServerConnection.OnError += (string Error) =>
        {
            ConnectionError = true;
            ErrorMessage    = Error;
        };

        //Register connection closed event
        ServerConnection.OnClose += (WebSocketCloseCode Code) =>
        {
            ConnectionClosed = true;
            CloseCode        = Code.ToString();
        };
    }
Esempio n. 23
0
        public WebSocket(string url, Dictionary <string, string> headers = null)
        {
            if (!WebSocketFactory.isInitialized)
            {
                WebSocketFactory.Initialize();
            }

            int instanceId = WebSocketFactory.WebSocketAllocate(url);

            WebSocketFactory.instances.Add(instanceId, this);

            this.instanceId = instanceId;
        }
Esempio n. 24
0
        // ChatPageViewModel vm;
        public ChatPage()
        {
            //InitializeComponent ();
            //         BindingContext = vm = new ChatPageViewModel("Lil Pump");
            InitializeComponent();

            // Get a websocket from your PCL library via the factory
            _connection            = WebSocketFactory.Create();
            _connection.OnOpened  += Connection_OnOpened;
            _connection.OnMessage += Connection_OnMessage;
            _connection.OnClosed  += Connection_OnClosed;
            _connection.OnError   += Connection_OnError;
        }
Esempio n. 25
0
        public static WebSocketServer Create <T>(string name, string origin, int interval = 20, string server = "localhost", int port = 8181) where T : IStreamableElementFactory, new()
        {
            // create the server
            var srv = new WebSocketServer("ws://" + server + ":" + port, origin);
            //srv.RegisterHandler<ElementSocket<T>>("/" + name);

            var wsf = new WebSocketFactory(srv);

            wsf.Register <ElementSocket <T> >("/" + name);

            srv.Start();
            return(srv);
        }
Esempio n. 26
0
        public Task <bool> Connect(string url, string protocol = null)
        {
            var             tcs     = new TaskCompletionSource <bool>();
            Action          onOpen  = null;
            Action          onClose = null;
            Action <string> onError = null;

            onOpen = () => {
                AVRealtime.PrintLog("PCL websocket opened");
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                // 注册事件
                connection.OnMessage += Connection_OnMessage;
                connection.OnClosed  += Connection_OnClosed;
                connection.OnError   += Connection_OnError;
                tcs.SetResult(true);
            };
            onClose = () => {
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                tcs.SetException(new Exception("连接关闭"));
            };
            onError = (err) => {
                AVRealtime.PrintLog(string.Format("连接错误:{0}", err));
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                try {
                    connection.Close();
                } catch (Exception e) {
                    AVRealtime.PrintLog(string.Format("关闭错误的 WebSocket 异常:{0}", e.Message));
                } finally {
                    tcs.SetException(new Exception(string.Format("连接错误:{0}", err)));
                }
            };

            // 在每次打开时,重新创建 WebSocket 对象
            connection           = WebSocketFactory.Create();
            connection.OnOpened += onOpen;
            connection.OnClosed += onClose;
            connection.OnError  += onError;
            //
            if (!string.IsNullOrEmpty(protocol))
            {
                url = string.Format("{0}?subprotocol={1}", url, protocol);
            }
            connection.Open(url, protocol);
            return(tcs.Task);
        }
Esempio n. 27
0
 public void Open(string url, string protocol = null)
 {
     // 在每次打开时,重新创建 WebSocket 对象
     connection            = WebSocketFactory.Create();
     connection.OnOpened  += Connection_OnOpened;
     connection.OnMessage += Connection_OnMessage;
     connection.OnClosed  += Connection_OnClosed;
     connection.OnError   += Connection_OnError;
     if (!string.IsNullOrEmpty(protocol))
     {
         url = string.Format("{0}?subprotocol={1}", url, protocol);
     }
     connection.Open(url, protocol);
 }
Esempio n. 28
0
        public void Connect(string url)
        {
            if (mSocketClient != null)
            {
                throw new Exception("Please disconnect the connected/connecting WebScoket.");
            }

            mHost                    = url;
            mSocketClient            = WebSocketFactory.CreateInstance(url);
            mSocketClient.OnOpen    += OnConnected;
            mSocketClient.OnClose   += OnDisconnected;
            mSocketClient.OnMessage += OnMessage;
            mSocketClient.OnError   += OnError;
            mSocketClient.Connect();
        }
Esempio n. 29
0
        public void Dispose()
        {
            _websocket.OnMessage -= OnMessageReceive;
            _websocket.OnOpened  -= OnOpened;
            _websocket.OnClosed  -= OnClosed;
            _websocket.OnError   -= OnError;

            ServerAddress = null;
            _messageQueue.Clear();
            _messageQueue = null;

            Disconnect();
            _websocket?.Dispose();
            _websocket = null;
            WebSocketFactory.DisposeAll();
        }
Esempio n. 30
0
        private void Start()
        {
            _wsClient = WebSocketFactory.CreateInstance(ConnectTarget);

            _wsClient.OnOpen += () => { Debug.Log("Connected GMC server"); };

            _wsClient.OnMessage += (byte[] msg) =>
            {
                Debug.Log($"{System.Text.Encoding.UTF8.GetString(msg)}");
                OnGetGmcMessage?.Invoke(msg);
            };

            _wsClient.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); };

            _wsClient.Connect();
        }