Send() public method

Sends the specified file as the binary data using the WebSocket connection.
/// The current state of the connection is not Open. /// /// is . /// /// /// The file does not exist. /// /// /// -or- /// /// /// The file could not be opened. /// ///
public Send ( FileInfo fileInfo ) : void
fileInfo System.IO.FileInfo /// A that specifies a file to send. ///
return void
Ejemplo n.º 1
1
        public int ConnectToWebSocket()
        {
            ws = new WebSocket(_Address);

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1500;
            timer.Tick += (sender, e) =>
            {
                if (ws != null)
                    ws.Send(JsonConvert.SerializeObject(new { type = "getframe" }));
            };

            ws.OnMessage += Ws_OnMessage;
            ws.OnOpen += (sender, e) =>
            {
                //ws.Send(JsonConvert.SerializeObject(new { type = "getinfo" }));
                string msg = "{\"type\":\"getinfo\"}";
                ws.Send(msg);
            };
            ws.OnError += (sender, e) =>
                {
                    MessageBox.Show("Error during Websocket Connection: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ws.Close();
                    ws = null;
                    this.Dispose();
                };

            ws.Connect();
            if (Connected != null)
                Connected();
            timer.Start();

            return 0;
        }
        public HearbeatTransmitter(WebSocket socket, TimeSpan heartBeatInterval, Func<Dictionary<string, object>> onSendingHearbeat)
        {
            _socket = socket;
            _heartBeatInterval = heartBeatInterval;
            _onSendingHearbeat = onSendingHearbeat;

            Receive<string>(message =>
            {
                if (socket.ReadyState == WebSocketState.Open)
                {
                    var heartbeat = onSendingHearbeat();
                    heartbeat["$$Timestamp"] = DateTime.UtcNow;

                    var jsonPayload = JsonConvert.SerializeObject(new
                    {
                        Type = "Heartbeat",
                        Payload = heartbeat
                    });

                    socket.Send(jsonPayload);

                    Context.System.Scheduler.ScheduleTellOnce(heartBeatInterval, Self, "SendHeartbeat", Self);
                }
            }, msg => msg == "SendHeartbeat");
        }
Ejemplo n.º 3
0
 void OnApplicationQuit()
 {
     if (_ws != null && _isTracking && _hasInitiatedTracking)
     {
         _ws.Send(GazeIO.Request.toggleTracking);
     }
 }
 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");
     }
 }
        public void Send(ArraySegment <byte> data)
        {
            if (ReadyState != WebSocketSharp.WebSocketState.Open)
            {
                throw new WebSocketException("Socket is not open");
            }

            try
            {
                if (data.Offset > 0 || data.Count < data.Array.Length)
                {
                    // STA Websockets cant take offsets nor buffer lenghts.
                    byte[] buf = new byte[data.Count];
                    Buffer.BlockCopy(data.Array, data.Offset, buf, 0, data.Count);

                    Connection.Send(buf);
                }
                else
                {
                    Connection.Send(data.Array);
                }
            }
            catch (Exception e)
            {
                throw new WebSocketException("Unknown error while sending the message", e);
            }
        }
Ejemplo n.º 6
0
        public void Subscribe(AuthSubscriptionTopic topic)
        {
            var operation = "{\"op\":\"authKeyExpires\",\"args\":[\"" + topic.ApiKey + "\"," + topic.Expires + ",\"" + topic.Signature + "\"]}";

            _logger.Info(operation);

            _webSocket.Send(operation);
        }
Ejemplo n.º 7
0
 public void Send(String msg)
 {
     if (ws.ReadyState == WebSocketState.Open)
     {
         ws.Send(msg);
         log.Debug(ws.ToString() + " Message sent");
     }
 }
Ejemplo n.º 8
0
 void OnApplicationQuit()
 {
     if (_ws != null && isTracking && _hasInitiatedTracking)
     {
         _ws.Send(GazeIO.Request.toggleTracking);
     }
     if (_tobii != null)
     {
         _tobii.Close();
         _tobii = null;
     }
 }
Ejemplo n.º 9
0
 public void Close()
 {
     if (webSocket.IsAlive)
     {
         var json = requestAgent.CreateDisconnectAllJson();
         webSocket.Send(json);
     }
     webSocket.OnOpen    -= OnWebSocketOpen;
     webSocket.OnMessage -= OnWebSocketMessageReceive;
     webSocket.OnError   -= OnWebSocketError;
     webSocket.OnClose   -= OnWebSocketClose;
     webSocket.Close();
 }
Ejemplo n.º 10
0
        private void Ws_OnOpen(object sender, EventArgs e)
        {
            Log.Info("Successfully connected to lobby's bridge server");
            UIFrontendLoadingScreen.Get().StartDisplayError("connected to bridge server");
            MemoryStream stream = new MemoryStream();

            stream.WriteByte((byte)BridgeMessageType.InitialConfig);
            string addressAndPort = Artemis.ArtemisServer.Address + ":" + Artemis.ArtemisServer.Port;

            stream.Write(GetByteArray(addressAndPort), 0, addressAndPort.Length);

            byte[] buffer = stream.ToArray();
            ws.Send(buffer);
        }
Ejemplo n.º 11
0
        private void Authenticate()
        {
            var n = nonce;
            var authentication = new BitfinexAuthentication()
            {
                Event   = "auth",
                ApiKey  = apiKey,
                Nonce   = n,
                Payload = "AUTH" + n
            };

            authentication.Signature = ByteToString(encryptedSecret.ComputeHash(Encoding.ASCII.GetBytes(authentication.Payload)));

            Socket.Send(JsonConvert.SerializeObject(authentication));
        }
    public string Request(string resource, ERestMethod method, params string[] parameters)
    {
        _hasNewMessage = false;
        string request = CreateRequest(resource, method, parameters);

        _socket.Send(request);

        string response = string.Empty;

        switch (method)
        {
        case ERestMethod.GET:

            while (!_hasNewMessage)
            {
                DoNothing();
            }

            response = _message;

            break;
        }

        _hasNewMessage = false;
        return(response);
    }
Ejemplo n.º 13
0
 public static void Send(string message)
 {
     if (_webSocket != null)
     {
         _webSocket.Send(message);
     }
 }
Ejemplo n.º 14
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
        }
 /// <summary>
 /// Send a message to the WebSocket server.
 /// </summary>
 /// <param name="message">The message to send.</param>
 public override void SendMessage(string message)
 {
     if (_socket.IsAlive)
     {
         _socket.Send(message);
     }
 }
Ejemplo n.º 16
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());
            };
        }
Ejemplo n.º 18
0
        public override bool SendMessage(Message msg)
        {
            string json = Json.JsonConvert.SerializeObject(new MessageContainer {
                message = msg
            });

            if (IsServer)
            {
                try{
                    Server.WebSocketServices.Broadcast(json);
                }
                catch {
                    return(false);
                }
                return(true);
            }
            else
            {
                try{
                    Client.Send(json);
                }catch {
                    return(false);
                }
                return(true);
            }
        }
Ejemplo n.º 19
0
    }                                                      // added by TS

    public void Send(byte[] buffer)
    {
        if (buffer.Length > 22000)
        {
            return;
        }
        m_Socket.Send(buffer);
    }
Ejemplo n.º 20
0
 public void send(string msg)
 {
     // API change from IsConnected to IsAlive
     if (webSocket != null && webSocket.IsAlive)
     {
         webSocket.Send(msg);
     }
 }
Ejemplo n.º 21
0
 private void onHeartbeat(object state)
 {
     //Debug.WriteLine("HuyaChatApiMsg::onHeartbeat()");
     if (websocket != null && websocket.ReadyState == WebSocketSharp.WebSocketState.Open)
     {
         websocket.Send("ping");
     }
 }
Ejemplo n.º 22
0
 public void Send(byte[] buffer)
 {
     try {
         m_Socket.Send(buffer);
     } catch (Exception e) {
         Debug.LogException(e);
     }
 }
Ejemplo n.º 23
0
 private void _pingPongGame()
 {
     while (_running)
     {
         Thread.Sleep(2000);
         _socket.Send("{\"id\":199999,\"type\":\"ping\",}");
     }
 }
Ejemplo n.º 24
0
    public void getObjectsData(string checkNum)
    {
        Debug.Log("start getting data");
        ws.OnMessage += OnMessage;

        ws.Connect();
        ws.Send(checkNum);
    }
Ejemplo n.º 25
0
    private void SocketOpened(object sender, System.EventArgs e)
    {
        //invoke when socket opened

        Debug.Log("Connected");
        ws.Send("Hello from Unity");

        System.Collections.Generic.Dictionary <string, object> dict = new System.Collections.Generic.Dictionary <string, object>();
        dict.Add("Test", "Hello");
        dict.Add("name", config.name);
        dict.Add("roomSize", config.roomSize);

        Debug.Log(SimpleJson.SimpleJson.SerializeObject(dict));
        ws.Send(SimpleJson.SimpleJson.SerializeObject(dict));
        //ws.Send(UnityEngine.JsonUtility.ToJson(dict));
        //ws.Send(UnityEngine.JsonUtility.ToJson(config));

        isConnected = true;
    }
Ejemplo n.º 26
0
        public IEnumerator Send(string jsonString, GamebaseCallback.ErrorDelegate callback)
        {
            if (false == IsConnected())
            {
                yield return(GamebaseUnitySDKSettings.Instance.StartCoroutine(Reconnect((error) =>
                {
                    callback(error);

                    if (null == error)
                    {
                        socket.Send(jsonString);
                    }
                })));
            }
            else
            {
                socket.Send(jsonString);
            }
        }
Ejemplo n.º 27
0
        public IEnumerator Send(string jsonString, GamebaseCallback.ErrorDelegate callback)
        {
            if (false == IsConnected())
            {
                yield return(GamebaseCoroutineManager.StartCoroutine(GamebaseGameObjectManager.GameObjectType.WEBSOCKET_TYPE, Reconnect((error) =>
                {
                    callback(error);

                    if (null == error)
                    {
                        socket.Send(jsonString);
                    }
                })));
            }
            else
            {
                socket.Send(jsonString);
            }
        }
Ejemplo n.º 28
0
 private void SendSubscribeTopic(string msg)
 {
     if (isOpened && websocket.IsAlive)
     {
         websocket.Send(msg);
         if (!msg.Contains("ping"))
         {
             Console.WriteLine(msg);
         }
     }
 }
Ejemplo n.º 29
0
        public void OpenAndRegister(string serviceName)
        {
            if (!_WebSocket.IsAlive)
            {
                _WebSocket.Connect();
            }
            L4Logger.Info("Open BCR connection");
            XfsCommandBase <XfsCommand> xfsCommand = new XfsCommandBase <XfsCommand>
            {
                CommandType = CommandType.Open,
                ServiceType = ServiceTypes.BCR,
                XfsCommand  = new OpenCommand
                {
                    ServiceName = serviceName
                }
            };

            _WebSocket.Send(Newtonsoft.Json.JsonConvert.SerializeObject(xfsCommand, Formatting.Indented));
            ServiceName = serviceName;
        }
        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);
            }
        }
Ejemplo n.º 31
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);
            }
        }
Ejemplo n.º 32
0
        public DayWebSocketClient()
        {
            {
                // Set the WebSocket events.

                webSocket.OnOpen += (sender, e) => webSocket.Send("Hi, there!");

                webSocket.OnMessage += (sender, e) =>
                {
                    var body = !e.IsPing ? e.Data : "Received a ping.";
                    Console.WriteLine(body);
                    form_.updateMessage(body + "\n");
                };

                webSocket.OnError += (sender, e) =>
                {
                    Console.WriteLine(e.Message);
                    form_.updateMessage(e.Message);
                };

                webSocket.OnClose += (sender, e) =>
                {
                    Console.WriteLine(e.Reason);
                    form_.updateMessage(e.Reason);
                };
#if DEBUG
                // To change the logging level.
                webSocket.Log.Level = LogLevel.Trace;

                // To change the wait time for the response to the Ping or Close.
                webSocket.WaitTime = TimeSpan.FromSeconds(10);

                // To emit a WebSocket.OnMessage event when receives a ping.
                webSocket.EmitOnPing = true;
#endif
                // To enable the Per-message Compression extension.
            }
        }
Ejemplo n.º 33
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());
        }
Ejemplo n.º 34
0
        public void Authenticate()
        {
            string apiKey      = CurrentExchange.APIKey;
            string apiSecret   = CurrentExchange.APISecret;
            string authNonce   = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            string eventId     = "auth";
            string authPayload = "AUTH" + authNonce;
            string authSig     = GetHexHashSignature(authPayload, apiSecret).ToString();


            string payload = "{\"apiKey\":\"" + apiKey + "\",\"event\":\"auth\",\"authPayload\":\"" + authPayload + "\",\"authNonce\":" + authNonce + ",\"authSig\":\"" + authSig + "\"}";

            Socket.OnMessage += Socket_OnMessage;
            Socket.OnError   += Socket_OnError;
            Socket.OnOpen    += Socket_OnOpen;

            Socket.Connect();

            Socket.Send(payload);


            //string configpayload = "{   \"event\": \"conf\",   \"flags\": \"40 (32 XOR 8 = 40)\" }";

            //string subtrades = "{event: 'subscribe',channel: 'trades', symbol: BTCUSD}";

            //Socket.Send(subtrades);

            //Socket.Send(configpayload);

            //   Console.WriteLine("selling");
            // string payload2 = "[0, 'on', null,{ gid: 1,cid: " + authNonce + ",type: \"EXCHANGE MARKET\",symbol: \"tBTCUSD\",amount: -0.01,price: 899,hidden: 0}]";

            //    Socket.Send(payload2);
            //     Console.WriteLine("Sold");
            //  Console.Read();
            //  doneEvent.WaitOne();
        }
Ejemplo n.º 35
0
 private void btnSend_Click(object sender, EventArgs e)
 {
     try
     {
         var content = txtSend.Text;
         if (!string.IsNullOrEmpty(content))
         {
             client.Send(content);
         }
     }
     catch
     {
         chatBox.Items.Add("Cannot connect to server!");
     }
 }
Ejemplo n.º 36
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 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();
        }
      });
    }
Ejemplo n.º 38
0
        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();
        }
Ejemplo n.º 39
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();
		}
Ejemplo n.º 40
0
        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");
        }
Ejemplo n.º 41
0
#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();
        }
Ejemplo n.º 42
0
        private static WebSocket GetClient(ServantConfiguration configuration)
        {
            var url = "ws://" + configuration.ServantIoUrl + "/Client?installationGuid=" + configuration.InstallationGuid + "&organizationGuid=" + configuration.ServantIoKey + "&servername=" + System.Environment.MachineName;
            using (var ws = new WebSocket(url))
            {
                var serializer = new JavaScriptSerializer();
                var pingTimer = new System.Timers.Timer(2000);
                pingTimer.Elapsed += (sender, args) =>
                                     {
                                         ws.Ping();
                                     };
                pingTimer.Enabled = false;

                ws.OnMessage += (sender, e) =>
                {
                    var request = serializer.Deserialize<CommandRequest>(e.Data);

                    switch (request.Command)
                    {
                        case CommandRequestType.Unauthorized:
                            IsStopped = true;
                            Console.WriteLine();
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Servant.io key was not recognized.");
                            Console.ResetColor();
                            ws.Close();
                            break;
                        case CommandRequestType.GetSites:
                            var sites = SiteManager.GetSites();
                            var result = serializer.Serialize(sites);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid)
                                                     {
                                                         Guid = request.Guid,
                                                         Message = result,
                                                         Success = true
                                                     }));
                            break;
                        case CommandRequestType.UpdateSite:
                            var site = serializer.Deserialize<Site>(request.JsonObject);

                            var originalSite = SiteManager.GetSiteByName(request.Value);

                            if (originalSite == null)
                            {
                                ws.Send("not_found");
                                return;
                            }

                            originalSite.ApplicationPool = site.ApplicationPool;
                            originalSite.Name = site.Name;
                            originalSite.SiteState = site.SiteState;
                            originalSite.Bindings = site.Bindings;
                            originalSite.LogFileDirectory = site.LogFileDirectory;
                            originalSite.SitePath = site.SitePath;
                            originalSite.Bindings = site.Bindings;

                            SiteManager.UpdateSite(originalSite);

                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message  = "ok", Success = true}));
                            break;
                        case CommandRequestType.GetApplicationPools:
                            var appPools = SiteManager.GetApplicationPools();
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(appPools), Success = true}));
                            break;
                        case CommandRequestType.GetCertificates:
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(SiteManager.GetCertificates()), Success = true}));
                            break;
                        case CommandRequestType.StartSite:
                            var startSite = SiteManager.GetSiteByName(request.Value);
                            var startResult = SiteManager.StartSite(startSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Success = startResult == SiteStartResult.Started, Message = startResult.ToString() }));
                            break;
                        case CommandRequestType.StopSite:
                            var stopSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.StopSite(stopSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {  Success = true }));
                            break;
                        case CommandRequestType.RecycleApplicationPool:
                            var recycleSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.RecycleApplicationPoolBySite(recycleSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.RestartSite:
                            var restartSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.RestartSite(restartSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.DeleteSite:
                            var deleteSite = SiteManager.GetSiteByName(request.Value);
                            SiteManager.DeleteSite(deleteSite.IisId);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
                            break;
                        case CommandRequestType.CreateSite:
                            var createSite = serializer.Deserialize<Site>(request.JsonObject);
                            var id = SiteManager.CreateSite(createSite);
                            ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = id.ToString(), Success = true }));
                            break;
                    }
                };

                ws.OnError += (sender, args) =>
                {
                    var isInternalError = args.Message == "An exception has occurred while receiving a message.";

                    var socket = (WebSocket)sender;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + args.Message);
                    Console.ResetColor();

                    if (socket.ReadyState == WebSocketState.Open && !isInternalError)
                    {
                        Connect();
                    }
                };

                ws.OnClose += (sender, args) =>
                {
                    Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Lost connection to Servant.io");
                    pingTimer.Enabled = false;

                    if (!_isRetrying)
                    {
                        Connect();
                    }
                };

                ws.OnOpen += (sender, args) =>
                    {
                        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Successfully connected to ws://" + configuration.ServantIoUrl);
                        pingTimer.Enabled = true;
                    };
                ws.Log.Output = (data, s) => { };
                ws.Log.Level = LogLevel.Fatal;

                return ws;
            }
        }
Ejemplo n.º 43
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();
        }
Ejemplo n.º 44
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();
        }
Ejemplo n.º 45
0
 private void button5_Click(object _sender, EventArgs _e)
 {
     WebSocket wsEcho = new WebSocket("ws://localhost:4649/Echo");
     wsEcho.OnOpen += (sender, e) =>
     {
         wsEcho.Send("Hi, 张!");
     };
     wsEcho.OnMessage += (sender, e) =>
     {
         Debug.WriteLine(string.Format("wsGPS OnMessage => {0}", e.Data));
     };
     wsEcho.Connect();
 }
Ejemplo n.º 46
0
        public void Scarlet_WS_Initialise()
        {
            /* Scarlet Metrics */
            wsm = new ScarletMetrics();
            wsm.Send("Scarlet Service Started. (" + ip + ")");

            /* Server */
            var wssv = new WebSocketServer("ws://" + scarletURL + ":" + scarletPort);
            wssv.AddWebSocketService<Link>("/");
            wssv.Start();

            /* Client */
            ws = new WebSocket("ws://" + scarletURL + ":" + scarletPort);
            
            ws.Connect();

            ws.OnOpen += (sender, e) =>
            {
                ws.Send("Browser|Connected");
            };

            ws.OnMessage += (sender, e) =>
            {
                // Scarlet WS API
                // Words = (Browser/Updater)|(IP/*)|(Command)|(Perameters)
                string[] words = e.Data.Split('|');
                if (words[0] == "Updater")
                {
                    switch (words[1])
                    {
                        case ("browserConnect"):
                            Username = words[2];
                            key = ScarletAPI.Request("user", "info", words[2]);

                            if (backgroundWorker1.IsBusy == false)
                            {
                                ws.Send("Browser|browserConfirmation|free");
                            }
                            else
                            {
                                ws.Send("Browser|browserConfirmation|busy");
                            }
                            break;

                        case ("startDownload"):

                            installDirectory = words[2];
                            if (backgroundWorker1.IsBusy == false)
                            {
                                backgroundWorker1.RunWorkerAsync();
                            }
                            break;

                        case ("startVerify"):

                            verifyOnly = true;
                            installDirectory = words[2];
                            if (backgroundWorker1.IsBusy == false)
                            {
                                backgroundWorker1.RunWorkerAsync();
                            }
                            break;

                        case ("stopDownload"):

                            backgroundWorker1.CancelAsync();
                            break;

                        case ("locationChange"):
                            /*
                            installDirectory = words[2];
                            NameValueCollection postData = new NameValueCollection();
                            postData.Add("installDir", installDirectory);

                            ScarletAPI.PostRequest("user", "install", key, "", postData);
                            ws.Send("Browser|UpdateInstallLocation|" + installDirectory);
                            */
                            
                            ChooseFolder();

                            break;

                        case ("updateInstallLocation"):

                            installDirectory = words[2];
                            break;
                            
                        case ("broadcast"):
                            broadcast(words[3]);
                            break;

                        case ("fetchStatus"):

                            pushStatusToBrowser();
                            break;

                        case ("quit"):

                            Application.Exit();
                            break;

                        case ("restart"):

                            Program.restarting = true;
                            Application.Restart();
                            break;
                    }
                }
            };

            ws.OnClose += (sender, e) =>
            {
                ws.Connect();
            };

        }
Ejemplo n.º 47
0
 private bool sendMsgStopStream(WebSocket webSocket, int messageId)
 {
     webSocket.Send("{\"request-type\":\"StopStream\",\"message-id\":\"" + messageId.ToString() + "\"}");
     if (showDebugInfo)
         MessageBox.Show("Msg to OBS:" + "{\"request-type\":\"StopStream\",\"message-id\":\"" + messageId.ToString() + "\"}");
     return true;
 }
Ejemplo n.º 48
0
        public static void Main(string[] args)
        {
            // Create a new instance of the WebSocket class.
              //
              // The WebSocket class inherits the System.IDisposable interface, so you can
              // use the using statement. And the WebSocket connection will be closed with
              // close status 1001 (going away) when the control leaves the using block.
              //
              // If you would like to connect to the server with the secure connection,
              // you should create a new instance with a wss scheme WebSocket URL.

              using (var nf = new Notifier ())
              using (var ws = new WebSocket ("ws://echo.websocket.org"))
              //using (var ws = new WebSocket ("wss://echo.websocket.org"))
              //using (var ws = new WebSocket ("ws://localhost:4649/Echo"))
              //using (var ws = new WebSocket ("wss://localhost:5963/Echo"))
              //using (var ws = new WebSocket ("ws://localhost:4649/Echo?name=nobita"))
              //using (var ws = new WebSocket ("wss://localhost:5963/Echo?name=nobita"))
              //using (var ws = new WebSocket ("ws://localhost:4649/Chat"))
              //using (var ws = new WebSocket ("wss://localhost:5963/Chat"))
              //using (var ws = new WebSocket ("ws://localhost:4649/Chat?name=nobita"))
              //using (var ws = new WebSocket ("wss://localhost:5963/Chat?name=nobita"))
              {
            // Set the WebSocket events.

            ws.OnOpen += (sender, e) => ws.Send ("Hi, there!");

            ws.OnMessage += (sender, e) =>
            nf.Notify (
              new NotificationMessage {
                Summary = "WebSocket Message",
                Body = !e.IsPing ? e.Data : "Received a ping.",
                Icon = "notification-message-im"
              }
            );

            ws.OnError += (sender, e) =>
            nf.Notify (
              new NotificationMessage {
                Summary = "WebSocket Error",
                Body = e.Message,
                Icon = "notification-message-im"
              }
            );

            ws.OnClose += (sender, e) =>
            nf.Notify (
              new NotificationMessage {
                Summary = String.Format ("WebSocket Close ({0})", e.Code),
                Body = e.Reason,
                Icon = "notification-message-im"
              }
            );
            #if DEBUG
            // To change the logging level.
            ws.Log.Level = LogLevel.Trace;

            // To change the wait time for the response to the Ping or Close.
            //ws.WaitTime = TimeSpan.FromSeconds (10);

            // To emit a WebSocket.OnMessage event when receives a ping.
            //ws.EmitOnPing = true;
            #endif
            // To enable the Per-message Compression extension.
            //ws.Compression = CompressionMethod.Deflate;

            // To validate the server certificate.
            /*
            ws.SslConfiguration.ServerCertificateValidationCallback =
              (sender, certificate, chain, sslPolicyErrors) => {
            ws.Log.Debug (
              String.Format (
                "Certificate:\n- Issuer: {0}\n- Subject: {1}",
                certificate.Issuer,
                certificate.Subject
              )
            );

            return true; // If the server certificate is valid.
              };
             */

            // To send the credentials for the HTTP Authentication (Basic/Digest).
            //ws.SetCredentials ("nobita", "password", false);

            // To send the Origin header.
            //ws.Origin = "http://localhost:4649";

            // To send the cookies.
            //ws.SetCookie (new Cookie ("name", "nobita"));
            //ws.SetCookie (new Cookie ("roles", "\"idiot, gunfighter\""));

            // To connect through the HTTP Proxy server.
            //ws.SetProxy ("http://localhost:3128", "nobita", "password");

            // To enable the redirection.
            //ws.EnableRedirection = true;

            // Connect to the server.
            ws.Connect ();

            // Connect to the server asynchronously.
            //ws.ConnectAsync ();

            Console.WriteLine ("\nType 'exit' to exit.\n");
            while (true) {
              Thread.Sleep (1000);
              Console.Write ("> ");
              var msg = Console.ReadLine ();
              if (msg == "exit")
            break;

              // Send a text message.
              ws.Send (msg);
            }
              }
        }
Ejemplo n.º 49
0
        private void button1_Click(object sender1, EventArgs e1)
        {
            try
            {
                string destIP = this.cmbIP.Text;
                string patternIp = @"\b(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5])\b";
                if (destIP.Length <= 0 || !Regex.IsMatch(destIP, patternIp))
                {
                    return;
                }
                //ws = new WebSocket("ws://localhost:6110/Client");
                ws = new WebSocket("ws://" + destIP + ":4650");

                ws.OnOpen += (sender, e) =>
                {
                    //ws.Send("Hi, all!");
                    Debug.WriteLine("OnOpen => ...");
                };

                ws.OnMessage += (sender, e) =>
                {
                    string msg = e.Data;
                    Debug.WriteLine("OnMessage => " + msg);
                    command cmd_temp = (command)JsonConvert.DeserializeObject(msg, typeof(command));
                    IDevice device = findDevice(cmd_temp.TargetDevice);
                    if (device == null)
                    {
                        switch (cmd_temp.TargetDevice)
                        {
                            case TargetDeiveName.电风扇:
                                device = new FanDevice();
                                break;
                            case TargetDeiveName.电机:
                                device = new EngineDevice();
                                break;
                            case TargetDeiveName.绿灯:
                                device = new GreenLightDevice();
                                break;
                            case TargetDeiveName.红灯:
                                device = new RedLightDevice();
                                break;
                            case TargetDeiveName.黄灯:
                                device = new YellowLightDevice();
                                break;
                            case TargetDeiveName.GPS:
                                device = new GPSDevice();
                                break;
                            case TargetDeiveName.UHF:
                                device = new UHFDevice();
                                break;
                        }
                    }
                    if (device != null)
                    {
                        deviceList.Add(device);
                        device.setDevice(cmd_temp, cmd =>
                        {
                            string back = JsonConvert.SerializeObject(cmd);
                            Debug.WriteLine("*****  OnMessage <= " + back);
                            ws.Send(back);
                        });
                    }
                    //ws.Send(JsonConvert.SerializeObject(cmd_temp));
                };

                ws.OnError += (sender, e) =>
                {
                    Debug.WriteLine("OnError => " + e.Message);

                };

                ws.OnClose += (sender, e) =>
                {
                    Debug.WriteLine("OnClose => " + e.Data);

                };

                ws.Connect();

                //command cmd1 = new command(stateName.打开, "");
                //cmd1.TargetDevice = TargetDeiveName.绿灯;
                //cmd1.Initializing = "true";
                //this.initialCommandList.Add(cmd1);
                //sendInitialInfo(ws);
                //MCserver = new WebSocketServer(MCServerUrl);
                //MCserver.Start(socket =>
                //{
                //    socket.OnOpen = () =>
                //    {
                //        host.OnOpenWebSocket(socket);
                //    };
                //    socket.OnClose = () =>
                //    {
                //        host.OnCloseWebSocket(socket);
                //    };
                //    socket.OnMessage = message =>
                //    {
                //        host.OnMessage(message, socket);
                //    };
                //});

                this.initial_udp_server(Program.inputPort);
                检查设备状态(Program.getRemoteIPEndPoint(), 3000);

                this.button2.Enabled = true;
                this.button1.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 50
0
        public static void main()
        {
            log.Debug("D2MP starting...");

            ourDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            File.WriteAllText(Path.Combine(ourDir, "version.txt"), ClientCommon.Version.ClientVersion);
            var iconThread = new Thread(delegate()
                                        {
                                            using (icon = new ProcessIcon())
                                            {
                                                icon.Display();
                                                Application.Run();
                                            }
                                        });

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

            try
            {
                var steam = new SteamFinder();
                string steamDir = steam.FindSteam(true);
                dotaDir = steam.FindDota(true);
                if (steamDir == null || dotaDir == null)
                {
                    log.Fatal("Steam/dota was not found!");
                    return;
                }
                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);

                {
                    string[] dirs = Directory.GetDirectories(d2mpDir);
                    int i = 0;
                    foreach (string dir in dirs)
                    {
                        string modName = Path.GetFileName(dir);
                        log.Debug("Found mod: " + modName + " detecting version...");
                        string infoPath = Path.Combine(d2mpDir, modName + "/addoninfo.txt");
                        string versionFile = "";
                        if (File.Exists(infoPath))
                        {
                            versionFile = File.ReadAllText(infoPath);
                        }
                        Match 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);
                            mods.Add(new ClientMod {name = modName, version = version});
                        }
                        else
                        {
                            log.Error("Can't find version info for mod: " + modName + ", not including");
                        }
                        i++;
                    }
                }

                //Detect user
                string config = File.ReadAllText(Path.Combine(steamDir, @"config\config.vdf"));
                MatchCollection matches = Regex.Matches(config, "\"\\d{17}\"");
                string steamid;
                var 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.");

                var 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 < 240 && !shutDown)
                {
                    using (ws = new WebSocket(server))
                    {
                        ws.OnMessage += (sender, e) =>
                                        {
                                            log.Debug("server: " + e.Data);
                                            JObject msg = JObject.Parse(e.Data);

                                            switch (msg["msg"].Value<string>())
                                            {
                                                case Shutdown.Msg:
                                                    log.Debug("Shutting down due to server request.");
                                                    shutDown = true;
                                                    return;
                                                case ClientCommon.Methods.Uninstall.Msg:
                                                    log.Debug("Uninstalling due to server request...");
                                                    Uninstall();
                                                    shutDown = true;
                                                    return;
                                                case ClientCommon.Methods.InstallMod.Msg:
                                                    ThreadPool.QueueUserWorkItem(InstallMod, msg.ToObject<InstallMod>());
                                                    break;
                                                case ClientCommon.Methods.DeleteMod.Msg:
                                                    ThreadPool.QueueUserWorkItem(DeleteMod, msg.ToObject<DeleteMod>());
                                                    break;
                                                case ClientCommon.Methods.SetMod.Msg:
                                                    ThreadPool.QueueUserWorkItem(SetMod, msg.ToObject<SetMod>());
                                                    break;
                                                case ClientCommon.Methods.ConnectDota.Msg:
                                                    ThreadPool.QueueUserWorkItem(ConnectDota, msg.ToObject<ConnectDota >());
                                                    break;
                                                case ClientCommon.Methods.LaunchDota.Msg:
                                                    ThreadPool.QueueUserWorkItem(LaunchDota, msg.ToObject<LaunchDota>());
                                                    break;
                                                case ClientCommon.Methods.ConnectDotaSpectate.Msg:
                                                    ThreadPool.QueueUserWorkItem(SpectateGame, msg.ToObject<ConnectDotaSpectate>());
                                                    break;
                                                default:
                                                    log.Error("Command not recognized.");
                                                    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;
                        }

                        log.Debug("Sending init, version: " + ClientCommon.Version.ClientVersion);
                        var init = new Init { SteamIDs = steamids.ToArray(), Version = ClientCommon.Version.ClientVersion, Mods = mods.ToArray() };
                        var json = JObject.FromObject(init).ToString(Formatting.None);
                        ws.Send(json);

                        icon.DisplayBubble(tryCount > 1
                            ? "Reconnected!"
                            : "Connected and ready to begin installing mods.");

                        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();
        }
Ejemplo n.º 51
0
        private void InitialiseSocket()
        {
            socket = new WebSocket("ws://qa.sockets.stackexchange.com");
            socket.OnError += (o, oo) =>
            {
                if (OnException != null)
                {
                    OnException(oo.Exception);
                }
            };
            // SE site IDs (may come in handy later on).
            // 415,520,139,477,540,11,41,118,463,89,514,528,532,320,126,375,308,502,147,565,431,435,371,304,605,196,597,391,571,363,419,563,65,281,557,182,220,553,530,591,135,583,595,97,481,546,471,500,299,53,269,467,79,253,174,607,567,587,324,73,156,162,455,524,257,555,336,593,312,479,403,387,548,69,504,4,248,224,367,601,240,615,496,498,228,93,277,518,265,61,216,151,379,475,131,200,208,559,204,447,489,469,122,451,459,186,49,2,232,295,212,244,536,512,508,353,411,101,1,526,609,573,3,483,85,395,423,114,516,273,485,106,102,599,170,34,45,427,603,110,579,166,613,581
            socket.OnOpen += (o, oo) => socket.Send("155-questions-active");
            socket.OnMessage += (o, message) =>
            {
                if (OnActiveQuestion == null && OnActiveAnswer == null) return;

                try
                {
                    Task.Factory.StartNew(() =>
                    {
                        CQ dom;
                        var question = PostFetcher.GetQuestion(message, out dom);
                        var answer = PostFetcher.GetLatestAnswer(dom, question.Url);

                        if (OnActiveQuestion != null && answer == null)
                        {
                            OnActiveQuestion(question);
                            return;
                        }

                        if (OnActiveAnswer != null)
                        {
                            OnActiveAnswer(answer);
                        }
                    });
                }
                catch (Exception ex)
                {
                    if (OnException != null)
                    {
                        OnException(ex);
                    }
                }
            };

            socket.OnClose += (o, oo) =>
            {
                if (disposed) { return; }

                InitialiseSocket();
            };
        }
Ejemplo n.º 52
0
        public void ConnectAndReadMessages()
        {
            CurrentGatewayURL = GetGatewayUrl();
            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"):
                            using (var sw = new StreamWriter("READY_LATEST.txt"))
                                sw.Write(message);
                            Me = new DiscordMember
                            {
                                user = new DiscordUser
                                {
                                    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()
                                }
                            };
                            ClientPrivateInformation.avatar = Me.user.avatar;
                            ClientPrivateInformation.username = Me.user.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 ("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.user.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 ("MESSAGE_DELETE"):
                            MessageDeletedEvents(message);
                            break;
                        case ("USER_UPDATE"):
                            UserUpdateEvents(message);
                            break;
                        case ("CHANNEL_UPDATE"):
                            ChannelUpdateEvents(message);
                            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 = this.token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);
                    Thread keepAlivetimer = new Thread(KeepAlive);
                    keepAlivetimer.Start();
                };
                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();
        }
Ejemplo n.º 53
0
        private void sendInitialInfo(WebSocket ws, command command)
        {
            ws.Send(JsonConvert.SerializeObject(command));

            //initialCommandList.ForEach(command =>
            //{
            //    ws.Send(JsonConvert.SerializeObject(command));
            //});
        }
Ejemplo n.º 54
0
    public static void Main (string [] args)
    {
      using (var nf = new Notifier ())
      using (var ws = new WebSocket ("ws://echo.websocket.org"))
      //using (var ws = new WebSocket ("wss://echo.websocket.org")) // For Secure Connection
      //using (var ws = new WebSocket ("ws://localhost:4649/Echo"))
      //using (var ws = new WebSocket ("wss://localhost:4649/Echo"))
      //using (var ws = new WebSocket ("ws://localhost:4649/Echo?name=nobita"))
      //using (var ws = new WebSocket ("ws://localhost:4649/Chat"))
      //using (var ws = new WebSocket ("wss://localhost:4649/Chat"))
      //using (var ws = new WebSocket ("ws://localhost:4649/Chat?name=nobita"))
      {
        /* Setting WebSocket events */
        ws.OnOpen += (sender, e) => ws.Send ("Hi, there!");

        ws.OnMessage += (sender, e) =>
          nf.Notify (
            new NotificationMessage {
              Summary = "WebSocket Message",
              Body = e.Data,
              Icon = "notification-message-im"
            });

        ws.OnError += (sender, e) =>
          nf.Notify (
            new NotificationMessage {
              Summary = "WebSocket Error",
              Body = e.Message,
              Icon = "notification-message-im"
            });

        ws.OnClose += (sender, e) =>
          nf.Notify (
            new NotificationMessage {
              Summary = String.Format ("WebSocket Close ({0})", e.Code),
              Body = e.Reason,
              Icon = "notification-message-im"
            });
         
#if DEBUG
        // Changing the logging level
        ws.Log.Level = LogLevel.Trace;
#endif
        // Setting Per-message Compression
        //ws.Compression = CompressionMethod.Deflate;

        /* For Secure Connection
        ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
          ws.Log.Debug (String.Format ("\n{0}\n{1}", certificate.Issuer, certificate.Subject));
          return true; // If the server cert is valid
        };
         */

        // For HTTP Authentication (Basic/Digest)
        //ws.SetCredentials ("nobita", "password", false);

        // Setting Origin header
        //ws.Origin = "http://echo.websocket.org";
        //ws.Origin = "http://localhost:4649";

        // Setting Cookies
        //ws.SetCookie (new Cookie ("name", "nobita"));
        //ws.SetCookie (new Cookie ("roles", "\"idiot, gunfighter\""));

        // Setting Proxy
        //ws.SetProxy ("http://localhost:3128", "nobita", "password");

        // Connecting to the server
        ws.Connect ();
        //ws.ConnectAsync ();

        Console.WriteLine ("\nType 'exit' to exit.\n");
        while (true) {
          Thread.Sleep (1000);
          Console.Write ("> ");
          var msg = Console.ReadLine ();
          if (msg == "exit")
            break;

          // Sending a text message
          ws.Send (msg);
        }
      }
    }
Ejemplo n.º 55
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..");
        }
Ejemplo n.º 56
0
        public static void Main(string[] args)
        {
            var ts = new ThreadState();

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

              if (_msgQ.Count > 0)
              {
            var msg = (NfMessage)_msgQ.Dequeue();
            #if NOTIFY
            var 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 (var ws = new WebSocket("ws://echo.websocket.org", "echo"))
              //using (var ws = new WebSocket("wss://echo.websocket.org", "echo"))
              //using (var ws = new WebSocket("ws://localhost:4649"))
              //using (var ws = new WebSocket("ws://localhost:4649/Echo"))
              //using (var ws = new WebSocket("wss://localhost:4649/Echo"))
              //using (var ws = new WebSocket("ws://localhost:4649/Echo?name=nobita"))
              //using (var ws = new WebSocket("ws://localhost:4649/エコー?name=のび太"))
              //using (var ws = new WebSocket("ws://localhost:4649/Chat"))
              //using (var ws = new WebSocket("ws://localhost:4649/Chat?name=nobita"))
              //using (var ws = new WebSocket("ws://localhost:4649/チャット?name=のび太"))
              {
            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})", e.Code),
            e.Reason,
            "notification-message-im");
            };

            #if DEBUG
            ws.Log.Level = LogLevel.TRACE;
            #endif
            //ws.Compression = CompressionMethod.DEFLATE;
            //ws.Origin = "http://echo.websocket.org";
            //ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            //{
            //  ws.Log.Debug(String.Format("\n{0}\n{1}", certificate.Issuer, certificate.Subject));
            //  return true;
            //};
            //ws.SetCookie(new Cookie("nobita", "\"idiot, gunfighter\""));
            //ws.SetCookie(new Cookie("dora", "tanuki"));
            ws.Connect();
            //Console.WriteLine("Compression: {0}", ws.Compression);

            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.IsAlive)
              {
            break;
              }

              ws.Send(data);
            }
              }

              ts.Enabled = false;
              ts.Notification.WaitOne();
        }
Ejemplo n.º 57
0
        public static async void ConnectRohBot()
        {
            await Task.Run(() =>
            {
                Console.WriteLine("Logging into RohBot...");
                ws = new WebSocket("ws://fpp.literallybrian.com:12000/ws/");
                
                ws.OnOpen += (sender, args) =>
                {
                    var msg = new
                    {
                        Type = "auth",
                        Method = "login",
                        Username = RohBotUsername,
                        Password = RohBotPassword
                    };

                    ws.Send(JsonConvert.SerializeObject(msg));
                    ws.Send(JsonConvert.SerializeObject(new
                    {
                        Type = "sendMessage",
                        Target = "home",
                        Content = "/join manbot"
                    }));
                };

                ws.OnClose += (sender, args) =>
                {
                    Console.WriteLine("Lost connection to RohBot.");
                    Thread.Sleep(5000);
                    ConnectRohBot();
                };

                ws.OnError += (sender, args) => Console.WriteLine("F**K SHIT PISS " + args.Exception.ToString());

                ws.OnMessage += (sender, args) =>
                {
                    var msg = args.Data;
                    dynamic obj = JsonConvert.DeserializeObject(msg);

                    if (obj.Type == "sysMessage")
                    {
                        Console.WriteLine("(RohBot) \{obj.Content}");
                        return;
                    }

                    if (obj.Type != "message")
                        return;

                    var content = HttpUtility.HtmlDecode((string)obj.Line.Content);

                    if (content.Length > 32768)
                        return;

                    var parts = content.Split(new[] {':'}, 2);

                    if (parts.Length != 2) return;
                    if (parts[0].ToLower().Trim() != "manbot") return;

                    var response = new
                    {
                        Type = "sendMessage",
                        Target = "manbot",
                        Content = RunPat(parts[1])
                    };

                    ws.Send(JsonConvert.SerializeObject(response));
                };

                ws.Connect();
            });
Ejemplo n.º 58
0
        public void ConnectAndReadMessages()
        {
            ws = new WebSocket("wss://discordapp.com/hub");
                ws.OnMessage += (sender, e) =>
                {
                    var message = JObject.Parse(e.Data);
                    switch(message["t"].ToString())
                    {
                        case ("READY"):
                            using (var sw = new StreamWriter("READY"))
                                sw.Write(message);
                            Me = new DiscordMember { user = new DiscordUser { 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()} };
                            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 ("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.user.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;
#if DEBUG
                            default:
                            ni.BalloonTipText = "Check console! New message type!";
                            ni.ShowBalloonTip(10 * 1000);
                            Console.WriteLine(message);
                            break;
#endif
                    }
                };
                ws.OnOpen += (sender, e) => 
                {
                    DiscordInitObj initObj = new DiscordInitObj();
                    initObj.op = 2;
                    initObj.d.token = this.token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);
                    Thread keepAlivetimer = new Thread(KeepAlive);
                    keepAlivetimer.Start();
                };
                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();
        }
Ejemplo n.º 59
-1
        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) =>
            {
              ws.Send("Hi, all!");
            };

            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);
            }
              }
        }