Connect() public method

Establishes a WebSocket connection.
This method is not available in a server.
public Connect ( ) : void
return void
Example #1
0
        /* WS */
        public ScarletMetrics()
        {
            metricsws = new WebSocket("ws://" + MetricsWSURL + ":" + MetricsWSPort);

            metricsws.Connect();

            metricsws.OnOpen += (sender, e) =>
            {
                // Metrics - On Connection to the Metrics WS Reporting Server
                // Need to include username / IP in here as well.
                JsonObject jsonMessage = new JsonObject()
                    .add("type", "metrics")
                    .add("message", "connected");
                metricsws.Send(jsonMessage.ToString());
            };

            metricsws.OnMessage += (sender, e) =>
            {
            };

            metricsws.OnClose += (sender, e ) =>
                metricsws.Connect();

            metricsws.OnError += (sender, e) =>
                metricsws.Connect();
        }
        public static void pushSocket(string socketUrl, JObject socketObj)
        {
            if (ws == null)
            {
                ws = new WebSocketSharp.WebSocket(socketUrl);
            }
            if (ws.IsAlive == false)
            {
                LogClasses.LogProperties.info("WebSocket Is Alive : " + ws.IsAlive.ToString());
                ws.Connect();
            }

            if (ws.IsAlive == true)
            {
                LogClasses.LogProperties.info("socket data send: " + socketObj.ToString());
                ws.Send(socketObj.ToString());
            }
            ws.OnMessage += (sender, e) =>
            {
                LogClasses.LogProperties.info("WebSocket OnMessage : " + e.Data.ToString());
            };
            ws.OnClose += (sender, e) =>
            {
                LogClasses.LogProperties.error("WebSocket OnClose : CODE IS " + e.Code.ToString() + " reason is " + e.Reason.ToString());
                ws.Connect();
            };
            ws.OnError += (sender, e) =>
            {
                LogClasses.LogProperties.error("WebSocket OnError exception : " + e.Exception.ToString() + " message is : " + e.Message.ToString());
            };
        }
Example #3
0
        static void Main(string[] args)
        {
            ws.OnMessage += Ws_OnMessage;
            ws.OnClose   += Ws_OnClose;
            ws.OnError   += Ws_OnError;

            while (ws.IsAlive != true)
            {
                ws.Connect();
                Console.WriteLine("Is Alive : {0}", ws.IsAlive);
            }

            Console.ReadKey(true);
        }
Example #4
0
    void ConnectWS()
    {
        if (m_isWSConnected)
        {
            return;
        }

        m_Message = "No data.";

        var URL = "ws://bede6bd8.ngrok.io";

        //var URL = "ws://" + m_URL + ":" + m_Port;
        using (m_ws = new WebSocket(URL))
        {
            //m_ws.Log.Level = WebSocketSharp.LogLevel.TRACE;
            //m_ws.Log.File = "D:\\ws_log.txt";

            m_ws.OnOpen += (sender, e) =>
            {
                m_ws.Send(String.Format("Hello server."));
                Debug.Log("Connection opened.");
                m_isWSConnected = true;
            };
            m_ws.OnMessage += (sender, e) =>
            {
                m_Message = e.Data;
                //Debug.Log(m_Message);
            };
            m_ws.OnClose += (sender, e) =>
            {
                m_ws.Connect(); // This is a hack, but whatever
                m_isWSConnected = false;
            };
            m_ws.OnError += (sender, e) =>
            {
                // NOT PRINTING ERRORS
                //Debug.LogError(e.Message);
                m_isWSConnected = false;
            };

            m_ws.Connect();

            if (m_isWSConnected != true)
            {
                Debug.LogWarning("Unable to connect to:" + URL);
            }
        }
    }
        public int Connect(string node_url = "")
        {
            var connectionString = node_url.Equals(string.Empty) ? Consts.WssConnectionString : node_url;
            var certList         = GetCertificatesFromPem(Consts.CertFileName);

            _wss = new WebSocketSharp.WebSocket(connectionString);

            _wss.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            _wss.SslConfiguration.ClientCertificates  = new X509CertificateCollection(certList);
            _wss.SslConfiguration.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => {
                // If the server certificate is valid.
                return(sslPolicyErrors == SslPolicyErrors.None);
            };

            _wss.OnMessage += (sender, e) => {
                var payload = e.Data;
                _logger.Info($"WS Received Message: {payload}");
                foreach (var item in _observers)
                {
                    item.HandleMessage(payload);
                }
            };

            _wss.Connect();
            _logger.Info($"Connected to {connectionString}");

            return(0);
        }
Example #6
0
        public static void Main(string[] args)
        {
            if (args.Length != 1) {
                Console.Error.WriteLine ("ERROR: need a valid Websocket URL");
                Environment.Exit (-1);
            }

            using (var ws = new WebSocket (args[0])) {
                Int64 syncCtr = 0;
                ws.OnMessage += (sender, e) => {
                    Console.WriteLine (e.Data);
                    Interlocked.Decrement (ref syncCtr);
                };
                ws.Connect ();
                if (!ws.IsAlive) {
                    Console.Error.WriteLine ("ERROR: Could not connect to Websocket Server {0}", args[0]);
                    Environment.Exit(-2);
                }

                var input = "";
                while (string.Compare (input.Trim (), "shutdown", true) != 0) {
                    if (!string.IsNullOrWhiteSpace (input)) {
                        ws.Send (input.Trim());
                        Interlocked.Increment (ref syncCtr);

                        while (Interlocked.Read (ref syncCtr) > 0) {
                            Thread.Sleep (1);
                        }
                    }
                    Console.Write ("Type in a message or 'shutdown' to quit: ");
                    input = Console.ReadLine ();
                } // Longevity loop
            } // using
        }
Example #7
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
            Excel.Range firstRow = activeWorksheet.get_Range("A1");
            firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
            Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
            newFirstRow.Value2 = "lETS START THIS THING";

            //lets start this thing
            using (var ws = new WebSocket("ws://dumbsocket.herokuapp.com"))
            {
                ws.OnError += (error_sender, error_e) => {
                    Console.Write("socket error");
                    //SOME BROKE SHIT
                };

                ws.OnOpen += (open_sender, open_e) => {
                    Console.Write("sockets open");
                   //windows open
                };

                ws.OnClose += (close_sender, close_e) => {
                    Console.Write("socket closed");
                };

                ws.OnMessage += (socket_sender, socket_e) =>
                {
                    newFirstRow.Value2 = "This is coming from the websocket" + socket_e.Data;
                };

                ws.Connect();
            }
        }
Example #8
0
        private void BeginWebSocketClient(string stream, ICollection <ISymbol> symbols)
        {
            var newStreams = symbols.Select(s => $"{(Exchange.GetCurrencyCode(s.BaseCurrencyCode) + Exchange.GetCurrencyCode(s.QuoteCurrencyCode)).ToLower()}@{stream}");

            Streams.UnionWith(newStreams);

            if (WebSocketClient != null)
            {
                WebSocketClient = null;
            }

            WebSocketClient = new WebSocketSharp.WebSocket($"{Url}/stream?streams={string.Join('/', Streams)}");

            WebSocketClient.OnOpen += OnOpen;

            WebSocketClient.OnMessage += OnMessage;

            WebSocketClient.OnClose += delegate(object sender, WebSocketSharp.CloseEventArgs e)
            {
                OnClose?.Invoke(sender, new CloseEventArgs
                {
                    Code   = e.Code,
                    Reason = e.Reason
                });
            };

            WebSocketClient.Connect();
        }
 public void Websock_Client_Node()
 {
     if (Connect_Disconnect == false)
     {
         try
         {
             WebSocketClient            = new WebSocketSharp.WebSocket(serverUri.ToString());
             WebSocketClient.OnMessage += wsServer_NewDataReceived;
             WebSocketClient.OnOpen    += wsServer_NewSessionConnected;
             WebSocketClient.OnError   += wsServer_OnError;
             WebSocketClient.OnClose   += wsServer_Disconnect;
             WebSocketClient.Connect();
             Console.WriteLine("Connection Open");
             Connect_Disconnect = true;
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             Connect_Disconnect = false;
         }
     }
     else
     {
         WebSocketClient.Send("User is already connected");
     }
 }
Example #10
0
        public void InitServerInfo(string serverIp, string serverPort)
        {
            IsOpenned = false;
            L4Logger.Info("BCR InitServerInfo");
            if (_WebSocket != null)
            {
                _WebSocket.Close();
                _WebSocket.OnMessage -= _WebSocket_OnMessage;
            }
            this.ServerIP   = serverIp;
            this.ServerPort = serverPort;

            _WebSocket            = new WebSocketSharp.WebSocket(string.Format("ws://{0}:{1}/XfsCommandBehavior", ServerIP, ServerPort));
            _WebSocket.OnMessage += _WebSocket_OnMessage;
            _WebSocket.OnClose   += _WebSocket_OnClose;
            _WebSocket.OnError   += _WebSocket_OnError;
            _WebSocket.Connect();

            ReadDataCompleted = null;
            ReadDataError     = null;
            OpenCompleted     = null;
            RegisterCompleted = null;
            OpenError         = null;
            RegisterError     = null;
        }
Example #11
0
        static void TryConnect(int maxAttempts = -1)
        {
            Logger.Trace("Entering Command_Server TryConnect()");
            bool infAttempts = (maxAttempts == -1) ? true : false;

            conAttempts = 1;
            Timer timer = new Timer(1);

            timer.AutoReset = false;
            timer.Elapsed  += (source, e) => {
                Logger.Info($"Attempting to connect to Beat Saber ({conAttempts})...");

                ws.Connect();
                if (!ws.IsAlive && ((conAttempts <= maxAttempts) || infAttempts))
                {
                    conAttempts++;
                    ((Timer)source).Interval = 3000;
                    ((Timer)source).Start();
                }
                if (ws.IsAlive)
                {
                    ws.OnClose += onDisconnect;
                    Logger.Info("Connected to Beat Saber!");
                }
            };
            timer.Start();
        }
Example #12
0
 //needs to implemented from API
 /// <summary>
 /// 
 /// </summary>
 /// <param name="MessageReceived"></param>
 public ChatController(Model m)
 {
     ws = new WebSocket("ws://127.0.0.1:8005/chat");
     ws.OnMessage += (s, e) => GotPacket(e.Data);
     ws.Connect();
     this.m = m;
 }
Example #13
0
    public static void Connect(string url)
    {
        if (_webSocket == null)
        {
            _webSocket = new WebSocketSharp.WebSocket("ws://" + url + "/Echo");

            // Set the WebSocket events.
            _webSocket.OnMessage += (sender, e) =>
            {
                _instance.OnMessageReceived(e.Data);
            };

            _webSocket.OnError += (sender, e) =>
            {
                _instance.OnError(e.Message);
            };

            _webSocket.OnClose += (sender, e) =>
            {
                _instance.OnClosed();
            };

            _webSocket.Connect();
        }
    }
Example #14
0
        /// <summary>
        /// Connect in background
        /// </summary>
        private static void ConnectBackground()
        {
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                while (Program.client == null)
                {
                    try
                    {
                        WS.WebSocket client = new WS.WebSocket(Program.appSettings.WebsocketServerAddress);
                        client.WaitTime     = new TimeSpan(0, 0, 30);
                        client.Connect();

                        if (client.ReadyState != WS.WebSocketState.Open)
                        {
                            Program.client = null;
                        }
                        else
                        {
                            client.OnClose += (sender, e) => Program.ConnectBackground();
                            Program.client  = client;
                        }
                    }
                    catch (Exception ex)
                    {
                        Program.client = null;
                        ex.ToString();
                    }
                }
            }).Start();
        }
 public void Start(string address, int port, string path)
 {
     // IPAddress ipaddr = new IPAddress(address.Split('.').Select(a => (byte)a.to_i()).ToArray());
     // WebSocketServer wss = new WebSocketServer(ipaddr, port, this);
     wsc = new WebSocket(address + ":"+port+path, this);
     wsc.OnMessage += OnMessage;
     wsc.Connect();
 }
Example #16
0
 public void Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += (sender, e) => { lock (m_Messages) { m_Messages.Enqueue(e.RawData); } };
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message;
     m_Socket.Connect();
 }
 public void connect()
 {
     // Connect to the server.
     if (webSocket != null)
     {
         webSocket.Connect();
     }
 }
Example #18
0
    public void getObjectsData(string checkNum)
    {
        Debug.Log("start getting data");
        ws.OnMessage += OnMessage;

        ws.Connect();
        ws.Send(checkNum);
    }
Example #19
0
        public bool Connect()
        {
            socket.Connect();
            isConnected = socket.ReadyState == WebSocketState.Open;
            checkTimer.Start();

            return(isConnected);
        }
Example #20
0
        public void ConnectWebSocket(string Address)
        {
            Socket = new WebSocket(Address, "connection");
            Socket.OnOpen += ServerToClientConnected;
            Socket.OnMessage += ServerToClientOnMessage;
            Socket.OnClose += ServerToClientDisconnected;

            Socket.Connect();
        }
    public WebSocketRestClient(string endPoint, string contentType)
    {
        _endPoint    = endPoint;
        _contentType = contentType;

        _socket = new WebSocket(_endPoint);
        _socket.Connect();
        _socket.OnMessage += OnMessage;
    }
Example #22
0
		private void StartWebSocket ()
		{
			webSocket = new WebSocket (wsUri.AbsoluteUri);
			webSocket.Connect ();
			webSocket.OnOpen += WebSocket_OnOpen;
			webSocket.OnMessage += WebSocket_OnMessage;
			webSocket.OnClose += WebSocket_OnClose;
			webSocket.OnError += WebSocket_OnError;
		}
Example #23
0
 private void button1_Click(object sender, EventArgs e)
 {
     ws = new WebSocket("ws://localhost:8080/?id=" + txtName.Text);
     ws.OnOpen += new EventHandler(ws_OnOpen);
     ws.OnMessage += new EventHandler<MessageEventArgs>(ws_OnMessage);
     ws.OnError += new EventHandler<ErrorEventArgs>(ws_OnError);
     ws.OnClose += new EventHandler<CloseEventArgs>(ws_OnClose);
     ws.Connect();
 }
Example #24
0
 private WebsocketManager()
 {
     UIFrontendLoadingScreen.Get().StartDisplayError("trying to connect to bridge server ", "at address: " + BridgeServerAddress);
     ws            = new WebSocketSharp.WebSocket(BridgeServerAddress);
     ws.OnMessage += Ws_OnMessage;
     ws.OnError   += Ws_OnError;
     ws.OnOpen    += Ws_OnOpen;
     ws.Connect();
 }
Example #25
0
 private static void Ws_OnError(object sender, ErrorEventArgs e)
 {
     Console.WriteLine("Exception on socket stream : {0}", e.Message);
     ws.Close();
     ws = new WebSocketSharp.WebSocket("ws://localhost:1346/CandleMarket");
     ws.Connect();
     ws.OnMessage += Ws_OnMessage;
     ws.OnClose   += Ws_OnClose;
     ws.OnError   += Ws_OnError;
 }
Example #26
0
        public async Task StreamAsync(Uri uri, CancellationToken token)
        {
            Throw.IfNull(uri, nameof(uri));

            if (!token.CanBeCanceled)
            {
                throw new ArgumentException("Token must be capable of being in the canceled state.", nameof(token));
            }

            token.ThrowIfCancellationRequested();

            IsStreaming = true;

            _webSocket            = new WebSocketSharp.WebSocket(uri.ToString());
            _webSocket.EmitOnPing = true;
            _webSocket.WaitTime   = TimeSpan.FromSeconds(30);

            _webSocket.OnMessage += WebSocket_OnMessage;
            _webSocket.OnError   += WebSocket_OnError;
            _webSocket.OnClose   += WebSocket_OnClose;

            try
            {
                try
                {
                    _webSocket.Connect();

                    if (_webSocket.ReadyState == WebSocketState.Open)
                    {
                        RaiseOpenEvent();
                    }
                }
                catch (OperationCanceledException) { }
                catch (Exception e)
                {
                    if (!token.IsCancellationRequested)
                    {
                        _logger?.LogError(e, $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket connect exception.");
                        throw;
                    }
                }
            }
            finally
            {
                IsStreaming = false;

                // NOTE: WebSocketState.CloseSent should not be encountered since CloseOutputAsync is not used.
                if (_webSocket.ReadyState == WebSocketState.Open || _webSocket.ReadyState == WebSocketState.Closing)
                {
                    _webSocket.Close();
                }

                RaiseCloseEvent();
            }
        }
        internal async Task ConnectAsync()
        {
            WebSocketClient = new WebSocketSharp.WebSocket(
                $"{Client.ClientOptions.WsOptions.GatewayUrl}?v={Client.ClientOptions.WsOptions.GatewayVersion}&encoding={Client.ClientOptions.WsOptions.EncodingType}");

            WebSocketClient.OnMessage += async(sender, msg) => { await _onWsMessage(sender, msg); };

            WebSocketClient.OnClose += _onWsClose;

            WebSocketClient.Connect();
        }
Example #28
0
 public void KlineWebSocket()
 {
     webSocket            = new WebSocketSharp.WebSocket($"wss://stream.binance.com:9443/ws/ethbtc@kline_1m");
     webSocket.OnMessage += (sender, e) =>
     {
         string jsonLine = e.Data.Replace(",[]", "");
         Console.WriteLine(jsonLine);
     };
     webSocket.OnError += (sender, e) => Console.WriteLine(e.Message);
     webSocket.Connect();
 }
        public static void Connect()
        {
            Console.Title = "Bot is starting";
            var ws = new WebSocketSharp.WebSocket(GetWSConnectionString());

            ws.OnMessage += (sender, e) => new RTMParseIncoming().OnIncomingMessage(sender, e);
            ws.OnOpen    += (sender, e) => OnOpen(sender, e);
            ws.Connect();
            ConnectedSocket = ws;
            Console.Title   = "Bot is running";
        }
Example #30
0
        public static void Main(string[] args)
        {
            //using (WebSocket ws = new WebSocket("ws://localhost:8000/"))
              using (WebSocket ws = new WebSocket("ws://localhost:8000/", "chat"))
              {
            /*ws.OnOpen += (o, e) =>
            {
              //Do something.
            };
             */
            ws.OnMessage += (o, s) =>
            {
            #if NOTIFY
              Notification nf = new Notification("[WebSocket] Message",
                                             s,
                                             "notification-message-im");
              nf.AddHint("append", "allowed");
              nf.Show();
            #else
              Console.WriteLine("[WebSocket] Message: {0}", s);
            #endif
            };

            ws.OnError += (o, s) =>
            {
              Console.WriteLine("[WebSocket] Error  : {0}", s);
            };

            /*ws.OnClose += (o, e) =>
            {
              //Do something.
            };
             */
            ws.Connect();

            Thread.Sleep(500);
            Console.WriteLine("\nType \"exit\" to exit.\n");

            string data;
            while (true)
            {
              Thread.Sleep(500);

              Console.Write("> ");
              data = Console.ReadLine();
              if (data == "exit")
              {
            break;
              }

              ws.Send(data);
            }
              }
        }
Example #31
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         client.Connect();
     }
     catch
     {
         chatBox.Items.Add("Cannot connect to server!");
     }
 }
Example #32
0
        static void TestClient()
        {
            using (var ws = new WebSocket("ws://localhost:8080/test1"))
            {
                ws.OnMessage += (sender, e) =>
                  Console.WriteLine("Laputa says: " + e.Data);

                ws.Connect();
                ws.Send("BALUS");
                Console.ReadKey(true);
            }
        }
Example #33
0
 public bool Connect(string url, string session)
 {
     socket = new WebSocket(url);
     socket.WaitTime = TimeSpan.FromSeconds(5);
     socket.OnOpen += Socket_OnOpen;
     socket.OnError += Socket_OnError;
     socket.OnMessage += Socket_OnMessage;
     socket.OnClose += Socket_OnClose;
     socket.Connect();
     reset.WaitOne();
     return IsConnected;
 }
Example #34
0
        private void ConnectWebSocket(RtmStartResponse rtmStartResponse)
        {
            if (rtmStartResponse == null || string.IsNullOrEmpty(rtmStartResponse.RtmUrl))
            {
                return;
            }

            WebSocketSharp.WebSocket socket = new WebSocketSharp.WebSocket(rtmStartResponse.RtmUrl);
            socket.OnMessage += socket_OnMessage;
            socket.OnOpen    += socket_OnOpen;
            socket.Connect();
        }
Example #35
0
 void Start()
 {
     Adress             += Ip + ":" + Port;
     m_Socket            = new WebSocketSharp.WebSocket(Adress);
     m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData);
     m_Socket.OnOpen    += (sender, e) => m_IsConnected = true;
     m_Socket.OnClose   += (sender, e) => m_IsConnected = false;
     m_Socket.OnError   += (sender, e) => m_Error = e.Message;
     m_Socket.ConnectAsync();
     Debug.Log("Init WebSocket");
     m_Socket.Connect();
 }
Example #36
0
        public async Task ClientCannotUseWrongProtolToConnectServer()
        {
            //Arrange
            const string clientAddress = "ws://localhost:54222/ws";
            const string serverAddress = "https://localhost:54222";

            var config           = NetCoreWebSocketHelper.CreateConfigWithUrl(serverAddress);
            var clientTestPassed = false;

            var serverAction = new Func <HttpContext, Task>(async httpContext =>
            {
                if (httpContext.Request.Path == "/ws")
                {
                    throw new Exception("Should not be able to create web socket connection successfully");
                }
            });

            var logger = new Logger(LogLevel.Debug, null, (logData, _) =>
            {
                var msg = logData.Message;
                _testOutputHelper.WriteLine(msg);
                if ("An exception has occurred while reading an HTTP request/response.".Equals(msg))
                {
                    clientTestPassed = true;
                }
            });

            //Act
            using (var server = NetCoreWebSocketHelper.CreateTestServer(config, _testOutputHelper, serverAction, true))
            {
                await server.StartAsync();

                using (var ws = new WebSocketSharp.WebSocket(clientAddress, logger))
                {
                    var testCompleted = false;
                    ws.OnError += (sender, args) =>
                    {
                        testCompleted = true;
                        Assert.True(args.Exception != null);
                    };

                    ws.OnOpen += (sender, args) =>
                    {
                        testCompleted = true;
                        Assert.True(false, "The connection doesn't use wss url should failed!");
                    };
                    ws.Connect();
                    SpinWait.SpinUntil(() => testCompleted, new TimeSpan(0, 0, 5));
                }
            }

            Assert.True(clientTestPassed);
        }
    void ConnectWS()
    {
        if (m_isWSConnected)
        {
            return;
        }

        m_Message = "No data.";

        using (m_ws = new WebSocket("ws://a9dd09be.ngrok.io"))
        {
            //m_ws.Log.Level = WebSocketSharp.LogLevel.TRACE;
            //m_ws.Log.File = "D:\\ws_log.txt";

            m_ws.OnOpen += (sender, e) =>
            {
                m_ws.Send(String.Format("Hello server."));
                Debug.Log("Connection opened.");
                m_isWSConnected = true;
            };
            m_ws.OnMessage += (sender, e) =>
            {
                m_Message = e.Data;
                //Debug.Log(m_Message);
            };
            m_ws.OnClose += (sender, e) =>
            {
                m_ws.Connect(); // This is a hack, but whatever
                m_isWSConnected = false;
            };
            m_ws.OnError += (sender, e) =>
            {
                // NOT PRINTING ERRORS
                //Debug.LogError(e.Message);
                m_isWSConnected = false;
            };

            m_ws.Connect();
        }
    }
 public void OpenClient()
 {
     if (_client != null)
     {
         _client.OnMessage -= OnRecievedMessage;
         _client.OnError -= OnError;
         _client.Close();
     }
     _client = new WebSocket(Settings.Default.Url);
     _client.OnMessage += OnRecievedMessage;
     _client.OnError += OnError;
     _client.Connect();
 }
Example #39
0
 public static void InternalConnect(String ipAddress)
 {
     try
     {
     webClient = new WebSocket("wss://" + ipAddress + ":3001");
     webClient.OnMessage += webClient_OnMessage;
     webClient.Connect();
     }
     catch (Exception ex)
     {
     Log.Error("Auto3D: " + ex.Message);
     }
 }
Example #40
0
    private void Connect_1(string addr)
    {
        if (sock != null && sock.IsConnected)
        {
            MessageEventManager.instance.BroadcastMessage(MessageType.ReLogin);
            return;
        }

        sock            = new WebSocketSharp.WebSocket(addr);
        sock.OnOpen    += OnPen_1;
        sock.OnMessage += OnMessage_1;
        sock.OnClose   += OnClose_1;
        sock.Connect();
    }
Example #41
0
        public void Connect()
        {
            lock (subscriptionLock)
            {
                Socket = new WebSocket(BaseAddress);
            }
            Socket.Log.Level  = LogLevel.Info;
            Socket.OnClose   += SocketClosed;
            Socket.OnError   += SocketError;
            Socket.OnOpen    += SocketOpened;
            Socket.OnMessage += SocketMessage;

            Socket.Connect();
        }
Example #42
0
        /// <summary>
        /// Makes this object and sets all it's needed properties
        /// </summary>
        /// <param name="url">The url</param>
        internal Connection(string url)
        {
            Url       = url;
            WebSocket = new WebSocket(url)
            {
                EmitOnPing        = false,
                EnableRedirection = true
            };

            WebSocket.OnMessage += Websocket_OnMessage;
            WebSocket.OnClose   += Websocket_OnClose;
            WebSocket.OnError   += Websocket_OnError;
            WebSocket.Connect();
        }
Example #43
0
        public void Connect(string accessToken, string apiKey, string region)
        {
            var url = Constants.URLs.GetWebsocketUrl(region);

            websocket = new WebSocketSharp.WebSocket(url);

            websocket.OnMessage += Websocket_OnMessage;
            websocket.Connect();
            IsConnected = true;

            var wsCredentialsPayload = new WsCredentialsPayload(accessToken, apiKey);

            websocket.Send(wsCredentialsPayload.AsJson());
        }
        private void Connect(string url)
        {
            if (_webSocket != null)
            {
                _webSocket.Close();
                _webSocket.OnMessage -= OnSocketMessage;
                _webSocket.OnClose -= OnSocketClose;
                _webSocket = null;
            }

            _webSocket = new WebSocket(url);
            _webSocket.OnMessage += OnSocketMessage;
            _webSocket.OnClose += OnSocketClose;
            _webSocket.Connect();
        }
    public WebSocketSharpServer(ServerSettings settings) {
      Settings = settings;
      Server = new WebSocketServer(Settings.Port);
      BaseUri = new Uri($"ws://localhost:{Server.Port}");
      Server.Start();
      Server.AddWebSocketService<Heartbeat>($"/{HeartbeatEndpoint}");
      Heartbeat = new WebSocket($"{BaseUri}{HeartbeatEndpoint}");
      Heartbeat.Connect();

      Task.Factory.StartNew(() => {
        while (!_isDisposing) {
          Heartbeat.Send("Heartbeat OK");
          Task.Delay(5000).Wait();
        }
      });
    }
        public WebSocketClientConnection(string host, int port, int timeoutMillis)
            : base(new WebSocketDevice(port, host))
        {
            this.timeout = timeoutMillis;

            socket = new WebSocket("ws://" + host + ":" + port + "/");
            socket.Log.Output = OnLog;
            socket.OnMessage += OnMessageReceived;

            socket.Connect();
            CheckError();

            // Say hi!
            socket.Send("HI:" + uuid);
            // Wait for hello...
            WaitMessage();
        }
Example #47
0
        //initializes the server
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (!connected)
            {
                client = new WebSocket(textBoxAddress.Text);
                client.OnOpen += (sender2, e2) =>
                    connected = true;
                client.OnClose += (sender2, e2) =>
                    connected = false;
                client.OnMessage += (sender2, e2) =>
                    Recievedlist.Add(e2.Data);
                client.OnError += (sender2, e2) =>
                    MessageBox.Show(((ErrorEventArgs)e2).Message);

                client.Connect();
            }
        }
Example #48
0
 public void BindAndAuthenticate(string token,
                         EventHandler OnOpen,
                         EventHandler<MessageEventArgs> OnMessage,
                         EventHandler<CloseEventArgs> OnClose,
                         EventHandler<ErrorEventArgs> OnError)
 {
     if (ws != null && ws.IsAlive)
     {
         ws.Close();
     }
     ws = new WebSocket(WebSocketServiceEndpointUrl);//ws://localhost:8080/?name=
     if (token == null) token = "";
     ws.SetCookie(new WebSocketSharp.Net.Cookie("token", token));
     ws.OnOpen += new EventHandler(OnOpen);
     ws.OnMessage += new EventHandler<MessageEventArgs>(OnMessage);
     ws.OnClose += new EventHandler<CloseEventArgs>(OnClose);
     ws.OnError += new EventHandler<ErrorEventArgs>(OnError);
     ws.Connect();
 }
Example #49
0
        public void Connect()
        {
            if(websocket != null || websocket.IsAlive) { return; }

            if(websocket != null)
            {
                websocket.Close();
                websocket = null;
            }

            using (websocket = new WebSocket(BaseAddress, new String[] { "lgpp-v1.0" }))
            {
                websocket.OnOpen += Websocket_OnOpen;
                websocket.OnMessage += Websocket_OnMessage;
                websocket.OnError += Websocket_OnError;
                websocket.OnClose += Websocket_OnClose;

                websocket.Connect();
            }
        }
        static void Main(string[] args)
        {
            using (var ws = new WebSocket("ws://localhost:8080/spring-websocket-stomp-apollo/chat/websocket"))
            {
                ws.OnMessage += ws_OnMessage;
                ws.OnOpen += ws_OnOpen;
                ws.OnError += ws_OnError;
                ws.Connect();
                Thread.Sleep(1000);

                StompMessageSerializer serializer = new StompMessageSerializer();

                var connect = new StompMessage("CONNECT");
                connect["accept-version"] = "1.2";
                connect["host"] = "";
                ws.Send(serializer.Serialize(connect));

                var clientId = RandomString(5);
                Console.WriteLine("Client Id :" + clientId);
                Thread.Sleep(1000);

                var sub = new StompMessage("SUBSCRIBE");
                sub["id"] = "sub-0";
                sub["destination"] = "/topic/broadcast";
                ws.Send(serializer.Serialize(sub));

                var sub1 = new StompMessage("SUBSCRIBE");
                sub1["id"] = "sub-1";
                sub1["destination"] = "/queue/message-" + clientId;
                ws.Send(serializer.Serialize(sub1));

                Thread.Sleep(1000);
                var content = new Content(){ Subject ="Stomp client", Message = "Hello World!!"};
                var broad = new StompMessage("SEND", JsonConvert.SerializeObject(content));
                broad["content-type"] = "application/json";
                broad["destination"] = "/app/broadcast";
                ws.Send(serializer.Serialize(broad));

                Console.ReadKey(true);
            }
        }
Example #51
0
        public AgarioClient()
        {
            Console.WriteLine(BitConverter.IsLittleEndian);
            state = new WorldState();
            credentials = Servers.GetFFAServer();

            Console.WriteLine("Server {0}", credentials.Server);
            Console.WriteLine("Key {0}", credentials.Key);

            var uri = "ws://" + credentials.Server;
            Console.WriteLine(uri);

            ws = new WebSocket(uri);

            ws.Origin = "http://agar.io";
            ws.OnOpen += OnOpen;
            ws.OnError += OnError;
            ws.OnMessage += OnMessageReceived;
            ws.OnClose += OnClose;
            ws.Connect();
        }
        static void EchoBack()
        {
            string res = null;
            using (var ws = new WebSocket ("ws://echo.websocket.org"))
            //using (var ws = new WebSocket ("ws://localhost:4649/Echo"))
            {
                var ver = Application.unityVersion;
                ws.OnOpen += (sender, e) =>
                    ws.Send (String.Format ("Hello, Unity {0}!", ver));

                ws.OnMessage += (sender, e) =>
                    res = e.Data;

                ws.OnError += (sender, e) =>
                    Debug.LogError (e.Message);

                ws.Connect ();
            }

            if (!res.IsNullOrEmpty())
                EditorUtility.DisplayDialog ("Echo Back Successfully!", res, "OK");
        }
Example #53
0
		public ChatClient(string url, string nick, string channel) {
			webSocket = new WebSocket(url);
			webSocket.OnOpen += (sender, e) =>
				webSocket.Send("{\"cmd\":\"join\",\"channel\":\"" + channel + "\",\"nick\":\"" + nick + "\"}");

			webSocket.OnMessage += (sender, args) => {
				var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(args.Data);
				if ((data["cmd"] as string == "chat") && (data["nick"] as string != nick)) {
					System.Diagnostics.Debug.WriteLine(args.Data);

					var chatArgs = new ChatEventArgs();
					chatArgs.Text = data["text"] as string;
					chatArgs.SenderNick = data["nick"] as string;
					chatArgs.SenderTrip = data["trip"] as string;

					//Console.WriteLine($"({data["trip"]}) {data["nick"]}: {data["text"]}");
					OnChat?.Invoke(this, chatArgs);
				}
			};

			webSocket.Connect();
		}
Example #54
0
        public Client(string identifier, Config configManager)
            : base(identifier, configManager)
        {
            // Create the bot user
            ServerUser = new User {
                Id = -1,
                Username = "******"
            };

            // Fetch server address from the config
            string server = Config.Get("Chat.Protocols.SockChat", "Address", "ws://enter_server_address_here");

            // Create the websocket object
            Socket = new WebSocket(server);

            // Assign the event listeners
            Socket.OnOpen += OnOpen;
            Socket.OnClose += OnClose;
            Socket.OnError += OnError;
            Socket.OnMessage += OnMessage;

            // Connect
            Socket.Connect();
        }
Example #55
0
        public EtzelClient(string host)
        {
            ws=new WebSocket (host);
            using ( ws ) {
                ws.OnMessage += (sender, e) => {
                    //Console.WriteLine (e.Data);
                    stupid s=JsonConvert.DeserializeObject<stupid>(e.Data);
                    if(s.cmd=="nomsg"){
                        this.isleep(s.qname);
                    }
                    if(s.cmd=="awk"){
                        this.fetch(s.qname);
                    }
                    if(s.cmd=="msg"){
                        this.qbacks[s.qname](s);
                        this.fetch(s.qname);
                    }

                };

            }

            ws.Connect ();
        }
Example #56
0
        public static void main()
        {
            log.Debug("D2MP starting...");

            ourDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var iconThread = new Thread(delegate()
            {
                using (icon = new ProcessIcon())
                {
                    icon.Display();
                    Application.Run();
                }
            });

            iconThread.SetApartmentState(ApartmentState.STA);
            iconThread.Start();

            try
            {
                var steam = new SteamFinder();
                var steamDir = steam.FindSteam(true);
                dotaDir = steam.FindDota(true);
                if (steamDir == null || dotaDir == null)
                {
                    log.Fatal("Steam/dota was not found!");
                    return;
                }
                else
                {
                    log.Debug("Steam found: " + steamDir);
                    log.Debug("Dota found: " + dotaDir);
                }

                addonsDir = Path.Combine(dotaDir, "dota/addons/");
                d2mpDir = Path.Combine(dotaDir, "dota/d2moddin/");
                modDir = Path.Combine(addonsDir, "d2moddin");
                if (!Directory.Exists(addonsDir))
                    Directory.CreateDirectory(addonsDir);
                if (!Directory.Exists(d2mpDir))
                    Directory.CreateDirectory(d2mpDir);
                if (!Directory.Exists(modDir))
                    Directory.CreateDirectory(modDir);

                {
                    var dirs = Directory.GetDirectories(d2mpDir);
                    modNames = new string[dirs.Length];
                    int i = 0;
                    foreach (var dir in dirs)
                    {
                        var modName = Path.GetFileName(dir);
                        log.Debug("Found mod: " + modName + " detecting version...");
                        var infoPath = Path.Combine(d2mpDir, modName + "/addoninfo.txt");
                        string versionFile = "";
                        if (File.Exists(infoPath))
                        {
                            versionFile = File.ReadAllText(infoPath);
                        }
                        var match = Regex.Match(versionFile, @"(addonversion)(\s+)(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)",
                                                RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            string version = match.Groups.Cast<Group>()
                                             .ToList()
                                             .Skip(3)
                                             .Aggregate("", (current, part) => current + part.Value);
                            log.Debug(modName + "=" + version);
                            modNames[i] = modName + "=" + version;
                        }
                        else
                        {
                            log.Error("Can't find version info for mod: " + modName + ", not including");
                            modNames[i] = modName + "=?";
                        }
                        i++;
                    }
                }

                //Detect user
                var config = File.ReadAllText(Path.Combine(steamDir, @"config\config.vdf"));
                var matches = Regex.Matches(config, "\"\\d{17}\"");
                string steamid;
                List<string> steamids = new List<string>();
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        steamid = match.Value.Substring(1).Substring(0, match.Value.Length - 2);
                        log.Debug("Steam ID detected: " + steamid);
                        steamids.Add(steamid);
                    }
                }
                else
                {
                    log.Fatal("Could not detect steam ID.");
                    return;
                }

                //Modify gameinfo.txt
                ModGameInfo();

                log.Debug("Starting shutdown file watcher...");
                string pathToShutdownFile = Path.Combine(ourDir, "d2mp.pid");
                File.WriteAllText(pathToShutdownFile, "Delete this file to shutdown D2MP.");

                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = ourDir;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                       | NotifyFilters.FileName;
                watcher.Filter = "d2mp.pid";
                watcher.Deleted += (sender, args) =>
                {
                    shutDown = true;
                };
                watcher.EnableRaisingEvents = true;

                shutDown = false;
                int tryCount = 0;
                while (tryCount < 30 && !shutDown)
                {
                    using (ws = new WebSocket(server))
                    {
                        ws.OnMessage += (sender, e) =>
                        {
                            log.Debug("server: " + e.Data);
                            if (e.Data == "invalidid")
                            {
                                log.Debug("Invalid ID!");
                                shutDown = true;
                                return;
                            }

                            if (e.Data == "close")
                            {
                                log.Debug("Shutting down due to server request.");
                                shutDown = true;
                                return;
                            }

                            if (e.Data == "uninstall")
                            {
                                log.Debug("Uninstalling due to server request...");
                                Uninstall();
                                shutDown = true;
                                return;
                            }

                            var msgParts = e.Data.Split(':');
                            switch (msgParts[0])
                            {
                                case "installmod":
                                    ThreadPool.QueueUserWorkItem(InstallMod, msgParts);
                                    break;
                                case "deletemod":
                                    ThreadPool.QueueUserWorkItem(DeleteMod, msgParts);
                                    break;
                                case "setmod":
                                    ThreadPool.QueueUserWorkItem(SetMod, msgParts);
                                    break;
                                case "dconnect":
                                    ThreadPool.QueueUserWorkItem(ConnectDota, msgParts);
                                    break;
                                case "launchdota":
                                    ThreadPool.QueueUserWorkItem(LaunchDota, msgParts);
                                    break;
                                case "dspectate":
                                    ThreadPool.QueueUserWorkItem(SpectateGame, msgParts);
                                    break;
                                default:
                                    log.Error("Command not recognized: " + msgParts[0]);
                                    break;
                            }
                        };

                        ws.OnOpen += (sender, e) => log.Debug("Connected");
                        ws.OnClose += (sender, args) => log.Debug("Disconnected");
                        ws.Connect();
                        tryCount++;
                        if (!ws.IsAlive)
                        {
                            if (tryCount == 1)
                            {
                                icon.DisplayBubble("Disconnected, attempting to reconnect...");
                            }
                            log.Debug("Can't connect to server, tries: " + tryCount);
                            Thread.Sleep(500);
                            continue;
                        }

                        if (tryCount > 1)
                        {
                            icon.DisplayBubble("Reconnected!");
                        }
                        else
                        {
                            icon.DisplayBubble("Connected and ready to begin installing mods.");
                        }

                        try
                        {
                            var ver =
                                File.ReadAllText(
                                    Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                 "version.txt"));
                            log.Debug("sending version: " + ver);
                            ws.Send("init:" + String.Join(",", steamids.ToArray(), 0, steamids.Count) + ":" + ver +
                                    ":" + String.Join(",", modNames));
                        }
                        catch (Exception ex)
                        {
                            log.Debug("Can't detect ID from version.txt, : " + ex);
                            return;
                        }

                        tryCount = 0;
                        while (ws.IsAlive && !shutDown)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                log.Fatal("Overall error in the program: " + ex);
            }
            UnmodGameInfo();
            Application.Exit();
        }
Example #57
0
        public async Task Connect(string slackKey)
        {
            this.SlackKey = slackKey;

            // disconnect in case we're already connected like a crazy person
            Disconnect();

            // kill the regex for our bot's name - we'll rebuild it upon request with some of the info we get here
            BotNameRegex = string.Empty;

            NoobWebClient client = new NoobWebClient();
            string json = await client.DownloadString("https://slack.com/api/rtm.start", RequestMethod.Post, "token", this.SlackKey);
            JObject jData = JObject.Parse(json);

            TeamID = jData["team"]["id"].Value<string>();
            TeamName = jData["team"]["name"].Value<string>();
            UserID = jData["self"]["id"].Value<string>();
            UserName = jData["self"]["name"].Value<string>();
            string webSocketUrl = jData["url"].Value<string>();

            UserNameCache.Clear();
            foreach (JObject userObject in jData["users"]) {
                UserNameCache.Add(userObject["id"].Value<string>(), userObject["name"].Value<string>());
            }
            
            // load the channels, groups, and DMs that margie's in
            Dictionary<string, SlackChatHub> hubs = new Dictionary<string, SlackChatHub>();
            ConnectedHubs = hubs;
            
            // channelz
            if (jData["channels"] != null) {
                foreach (JObject channelData in jData["channels"]) {
                    if (!channelData["is_archived"].Value<bool>() && channelData["is_member"].Value<bool>()) {
                        SlackChatHub channel = new SlackChatHub() {
                            ID = channelData["id"].Value<string>(),
                            Name = "#" + channelData["name"].Value<string>(),
                            Type = SlackChatHubType.Channel
                        };
                        hubs.Add(channel.ID, channel);
                    }
                }
            }

            // groupz
            if (jData["groups"] != null) {
                foreach (JObject groupData in jData["groups"]) {
                    if (!groupData["is_archived"].Value<bool>() && groupData["members"].Values<string>().Contains(UserID)) {
                        SlackChatHub group = new SlackChatHub() {
                            ID = groupData["id"].Value<string>(),
                            Name = groupData["name"].Value<string>(),
                            Type = SlackChatHubType.Group
                        };
                        hubs.Add(group.ID, group);
                    }
                }
            }

            // dmz
            if (jData["ims"] != null) {
                foreach (JObject dmData in jData["ims"]) {
                    string userID = dmData["user"].Value<string>();
                    SlackChatHub dm = new SlackChatHub() {
                        ID = dmData["id"].Value<string>(),
                        Name = "@" + (UserNameCache.ContainsKey(userID) ? UserNameCache[userID] : userID),
                        Type = SlackChatHubType.DM
                    };
                    hubs.Add(dm.ID, dm);
                }
            }

            // set up the websocket and connect
            WebSocket = new WebSocket(webSocketUrl);
            WebSocket.OnOpen += (object sender, EventArgs e) => {
                // set connection-related properties
                ConnectedSince = DateTime.Now;
            };
            WebSocket.OnMessage += async (object sender, MessageEventArgs args) => {
                await ListenTo(args.Data);
            };
            WebSocket.OnClose += (object sender, CloseEventArgs e) => {
                // set connection-related properties
                ConnectedSince = null;
                TeamID = null;
                TeamName = null;
                UserID = null;
                UserName = null;
            };
            WebSocket.Connect();
        }
Example #58
0
        public void Connect()
        {
            CurrentGatewayURL = GetGatewayUrl();
            DebugLogger.Log("Gateway retrieved: " + CurrentGatewayURL);
            ws = new WebSocket(CurrentGatewayURL);
            ws.EnableRedirection = true;
            ws.Log.File = "websocketlog.txt";
                ws.OnMessage += (sender, e) =>
                {
                    var message = JObject.Parse(e.Data);
                    switch(message["t"].ToString())
                    {
                        case ("READY"):
                            if(WriteLatestReady)
                                using (var sw = new StreamWriter("READY_LATEST.txt"))
                                    sw.Write(message);
                            //Me = new DiscordMember(this)
                            //{
                            //    user = new DiscordUser(this)
                            //    {
                            //        username = message["d"]["user"]["username"].ToString(),
                            //        id = message["d"]["user"]["id"].ToString(),
                            //        verified = message["d"]["user"]["verified"].ToObject<bool>(),
                            //        avatar = message["d"]["user"]["avatar"].ToString(),
                            //        discriminator = message["d"]["user"]["discriminator"].ToString(),
                            //        email = message["d"]["user"]["email"].ToString()
                            //    }
                            //};
                            Me = JsonConvert.DeserializeObject<DiscordMember>(message["d"]["user"].ToString());


                            ClientPrivateInformation.avatar = Me.Avatar;
                            ClientPrivateInformation.username = Me.Username;
                            HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                            GetChannelsList(message);
                            if (Connected != null)
                                Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it.
                            break;
                        case ("GUILD_MEMBER_REMOVE"):
                            GuildMemberRemoveEvents(message);
                            break;
                        case ("GUILD_MEMBER_ADD"):
                            GuildMemberAddEvents(message);
                            break;
                        case ("GUILD_DELETE"):
                            GuildDeleteEvents(message);
                            break;
                        case ("GUILD_CREATE"):
                            GuildCreateEvents(message);
                            break;
                        case ("GUILD_MEMBER_UPDATE"):
                            GuildMemberUpdateEvents(message);
                            break;
                        case ("GUILD_UPDATE"):
                            GuildUpdateEvents(message);
                            break;
                        case ("GUILD_ROLE_DELETE"):
                            GuildRoleDeleteEvents(message);
                            break;
                        case ("GUILD_ROLE_UPDATE"):
                            GuildRoleUpdateEvents(message);
                            break;
                        case ("PRESENCE_UPDATE"):
                            PresenceUpdateEvents(message);
                            break;
                        case ("MESSAGE_UPDATE"):
                            MessageUpdateEvents(message);
                            break;
                        case ("TYPING_START"):
                            DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                            if (server != null)
                            {
                                DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                                DiscordMember uuser = server.members.Find(x => x.ID == message["d"]["user_id"].ToString());
                                if (UserTypingStart != null)
                                    UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) });
                            }
                            break;
                        case ("MESSAGE_CREATE"):
                            MessageCreateEvents(message);
                            break;
                        case ("CHANNEL_CREATE"):
                            ChannelCreateEvents(message);
                            break;
                        case ("VOICE_STATE_UPDATE"):
                            VoiceStateUpdateEvents(message);
                            break;
                        case ("VOICE_SERVER_UPDATE"):
                            VoiceServerUpdateEvents(message);
                            break;
                        case ("MESSAGE_DELETE"):
                            MessageDeletedEvents(message);
                            break;
                        case ("USER_UPDATE"):
                            UserUpdateEvents(message);
                            break;
                        case ("CHANNEL_UPDATE"):
                            ChannelUpdateEvents(message);
                            break;
                        case ("CHANNEL_DELETE"):
                            ChannelDeleteEvents(message);
                            break;
                        case("MESSAGE_ACK"): //ignore this message, it's irrelevant
                            break;
                        default:
                            if (UnknownMessageTypeReceived != null)
                                UnknownMessageTypeReceived(this, new UnknownMessageEventArgs { RawJson = message });
                            break;
                    }
                };
                ws.OnOpen += (sender, e) => 
                {
                    DiscordInitObj initObj = new DiscordInitObj();
                    initObj.op = 2;
                    initObj.d.token = token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);

                    KeepAliveTaskToken = KeepAliveTaskTokenSource.Token;
                    KeepAliveTask = new Task(() => 
                    {
                        while (true)
                        {
                            DebugLogger.Log("Hello from inside KeepAliveTask! Sending..");
                            KeepAlive();
                            Thread.Sleep(HeartbeatInterval);
                            if (KeepAliveTaskToken.IsCancellationRequested)
                                KeepAliveTaskToken.ThrowIfCancellationRequested();
                        }
                    }, KeepAliveTaskToken, TaskCreationOptions.LongRunning);
                    KeepAliveTask.Start();
                    DebugLogger.Log("Began keepalive task..");
                };
                ws.OnClose += (sender, e) =>
                {
                    DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                    scev.Code = e.Code;
                    scev.Reason = e.Reason;
                    scev.WasClean = e.WasClean;
                    if (SocketClosed != null)
                        SocketClosed(this, scev);

                };
                ws.Connect();
            DebugLogger.Log("Connecting..");
        }
#pragma warning disable 1998
        public async Task Initiate()
        {
            VoiceDebugLogger.LogMessageReceived += (sender, e) =>
            {
                if (DebugMessageReceived != null)
                    DebugMessageReceived(this, e);
            };

            VoiceWebSocket = new WebSocket("wss://" + VoiceEndpoint.Replace(":80", ""));
            VoiceWebSocket.OnClose += (sender, e) =>
            {
                if (e.WasClean)
                    return; //for now, till events are hooked up
                VoiceDebugLogger.Log($"VoiceWebSocket Closed: (Code: {e.Code}) {e.Reason}", MessageLevel.Critical);
                Dispose();
            };
            VoiceWebSocket.OnError += (sender, e) =>
            {
                VoiceDebugLogger.Log($"VoiceWebSocket Error: {e.Message}", MessageLevel.Error);
                Dispose();
            };
            VoiceWebSocket.OnMessage += async (sender, e) =>
            {
                VoiceDebugLogger.Log(e.Data);

                JObject message = JObject.Parse(e.Data);
                if (message["op"].Value<int>() == 2)
                {
                    Params = new VoiceConnectionParameters();
                    Params.ssrc = message["d"]["ssrc"].Value<int>();
                    Params.port = message["d"]["port"].Value<int>();
                    JArray __modes = (JArray)message["d"]["modes"];
                    List<string> dynModes = new List<string>();
                    foreach (var mode in __modes)
                    {
                        dynModes.Add(mode.ToString());
                    }
                    Params.modes = dynModes.ToArray();
                    Params.heartbeat_interval = message["d"]["heartbeat_interval"].Value<int>();
                    await InitialConnection().ConfigureAwait(false);
                }
                else if (message["op"].Value<int>() == 4)
                {
                    string speakingJson = JsonConvert.SerializeObject(new { op = 5, d = new { speaking = true, delay = 0 } });
                    VoiceDebugLogger.Log("Sending initial speaking json..(" + speakingJson + ")");
                    VoiceWebSocket.Send(speakingJson);
                    Connected = true;

                    keepAliveTask = new Thread(() =>
                    {
                        if (Connected)
                        {
                            while (true)
                            {
                                //cancelToken.ThrowIfCancellationRequested();
                                SendKeepAlive().ConfigureAwait(false);
                                Thread.Sleep(Params.heartbeat_interval);
                            }
                        }
                    });

                    udpKeepAliveTask = new Thread(() =>
                    {
                        while (true)
                        {
                            SendUDPKeepAlive().ConfigureAwait(false);
                            Thread.Sleep(5000); //5 seconds
                        }
                    });

                    udpReceiveTask = new Thread(async () =>
                    {
                        try
                        {
                            while (_udp.Available > 0)
                            {
                                //byte[] packet = new byte[1920];
                                VoiceDebugLogger.Log("Received packet!!!!!! Length: " + _udp.Available);
                                //UdpReceiveResult d = await _udp.ReceiveAsync();
                                //packet = d.Buffer;

                                //VoiceDebugLogger.Log("sending speaking..");
                                //DiscordAudioPacket echo = DiscordAudioPacket.EchoPacket(packet, Params.ssrc);
                                //await _udp.SendAsync(echo.AsRawPacket(), echo.AsRawPacket().Length).ConfigureAwait(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Beep(32767, 1000);
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.StackTrace);
                        }
                    });

                    keepAliveTask.Start();
                    //udpKeepAliveTask.Start();
                    udpReceiveTask.Start();
                }
                else if (message["op"].Value<int>() == 5)
                {
                    if(Connected) //if not connected, don't worry about it
                    {
                        DiscordVoiceUserSpeakingEventArgs __args = new DiscordVoiceUserSpeakingEventArgs { Guild = _parent.GetServersList().Find(x=>x.id == this.Guild.id)};
                        __args.UserSpeaking = __args.Guild.members.Find(x => x.ID == message["d"]["user_id"].ToString());
                        __args.Speaking = message["d"]["speaking"].Value<bool>();

                        if (UserSpeaking != null)
                            UserSpeaking(this, __args);
                    }
                }
            };
            VoiceWebSocket.OnOpen += (sender, e) =>
            {
                VoiceDebugLogger.Log("VoiceWebSocket opened, sending initial json.");
                string initMsg = JsonConvert.SerializeObject(new
                {
                    op = 0,
                    d = new
                    {
                        user_id = Me.ID,
                        server_id = Guild.id,
                        session_id = SessionID,
                        token = Token
                    }
                });

                VoiceWebSocket.Send(initMsg);
            };
            VoiceWebSocket.Connect();
        }
Example #60
0
        public static void Main(string[] args)
        {
            ThreadState ts = new ThreadState();

              WaitCallback notifyMsg = state =>
              {
            while (ts.Enabled)
            {
              Thread.Sleep(500);

              if (_msgQ.Count > 0)
              {
            NfMessage msg = (NfMessage)_msgQ.Dequeue();
            #if NOTIFY
            Notification nf = new Notification(msg.Summary,
                                               msg.Body,
                                               msg.Icon);
            nf.AddHint("append", "allowed");
            nf.Show();
            #else
            Console.WriteLine("{0}: {1}", msg.Summary, msg.Body);
            #endif
              }
            }

            ts.Notification.Set();
              };

              ThreadPool.QueueUserWorkItem(notifyMsg);

              //using (WebSocket ws = new WebSocket("ws://echo.websocket.org", "echo"))
              //using (WebSocket ws = new WebSocket("wss://echo.websocket.org", "echo"))
              using (WebSocket ws = new WebSocket("ws://localhost:4649"))
              {
            ws.OnOpen += (sender, e) =>
            {
              ws.Send("Hi, all!");
            };

            ws.OnMessage += (sender, e) =>
            {
              if (!String.IsNullOrEmpty(e.Data))
              {
            enNfMessage("[WebSocket] Message", e.Data, "notification-message-im");
              }
            };

            ws.OnError += (sender, e) =>
            {
              enNfMessage("[WebSocket] Error", e.Message, "notification-message-im");
            };

            ws.OnClose += (sender, e) =>
            {
              enNfMessage(
            String.Format("[WebSocket] Close({0}:{1})", (ushort)e.Code, e.Code),
            e.Reason,
            "notification-message-im");
            };

            ws.Connect();

            Thread.Sleep(500);
            Console.WriteLine("\nType \"exit\" to exit.\n");

            string data;
            while (true)
            {
              Thread.Sleep(500);

              Console.Write("> ");
              data = Console.ReadLine();
              if (data == "exit")
              //if (data == "exit" || !ws.IsConnected)
              {
            break;
              }

              ws.Send(data);
            }
              }

              ts.Enabled = false;
              ts.Notification.WaitOne();
        }