Beispiel #1
0
        public static void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            Session session = (Session)sender;

            if ((session.fullUrl.IndexOf("-ws.va.huya.com") != -1 ? true : session.fullUrl.IndexOf("wsapi.huya.com") != -1))
            {
                HookMgr.LockByteArray(e.oWSM.PayloadData, string.Format("Mask={0} Fiddler原数据    ", e.oWSM.MaskingKey != null));
                byte[] arr = e.oWSM.PayloadAsBytes();
                HookMgr.LockByteArray(arr, string.Concat(string.Format("{0}  控制:{1} {2}", session.fullUrl, e.oWSM.FrameType, e.oWSM.IsFinalFrame), string.Format(" {0} Mask={1} Fiddler解Mask的    ", (e.oWSM.IsOutbound ? "发送" : "接收"), e.oWSM.MaskingKey != null)));
                WebSocket webs = session.__oTunnel as WebSocket;
                if (arr.Length != 0)
                {
                    try
                    {
                        XTrace.WriteLine(string.Format("消息列表 {0} 个", webs.listMessages.Count));
                        if (!e.oWSM.IsOutbound)
                        {
                            HookHyWebSocketNet.RecvData(arr);
                        }
                        else
                        {
                            HookHyWebSocketNet.SendData(arr);
                        }
                    }
                    catch (Exception exception)
                    {
                        XTrace.WriteLine(string.Concat("序列化包出错 ", exception.ToString()));
                    }
                }
            }
        }
        /// <summary>
        /// Routes the message specified within the event arguments, invoking any associated delegates where possible.
        /// </summary>
        /// <param name="client">The Stream Deck client.</param>
        /// <param name="e">The <see cref="WebSocketMessageEventArgs" /> instance containing the event data.</param>
        public Task RouteAsync(StreamDeckClient client, WebSocketMessageEventArgs e)
        {
            // determine if there is an event specified, and a delegate handler
            var jArgs = JObject.Parse(e.Message);

            if (!jArgs.TryGetString(nameof(StreamDeckEventArgs.Event), out var @event) ||
                !EventMethodCache.Value.TryGetValue(@event, out var @delegate))
            {
                this.Logger?.LogWarning("Unrecognised event received from Elgato Stream Deck: {0}", @event);
                return(Task.CompletedTask);
            }

            // determine the owner of the delegate, based on the event args
            var owner = this.TryGetActionInfo(jArgs, out var actionInfo)
                ? this.GetActionOrClient(jArgs, actionInfo, client)
                : client;

            try
            {
                return((Task)@delegate.Invoke(owner, new[] { jArgs.ToObject(@delegate.GetParameters()[0].ParameterType) }));
            }
            catch (Exception ex)
            {
                throw new ActionInvokeException(actionInfo.context, ex);
            }
        }
Beispiel #3
0
        protected virtual void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            //Debug.LogFormat("FTL socket {1} message:\n{0}", e.Data, e.IsBinary ? "binary" : "string");

            object obj = JsonValue.Parse(e.Data);

            if (obj is JsonArray)
            {
                Debug.Log("FTL Message Array received");
            }
            else if (obj is JsonObject)
            {
                JsonObject message = (JsonObject)obj;

                object op;

                if (message.TryGetValue(ProtocolConstants.OP_FIELD, out op))
                {
                    switch (Convert.ToInt32(op))
                    {
                    case ProtocolOpConstants.OP_HEARTBEAT:
                        //handleHeartbeat(message);
                        Debug.Log("** FTL Heartbeat Message");
                        break;

                    case ProtocolOpConstants.OP_WELCOME:
                        handleWelcome(message);
                        break;

                    case ProtocolOpConstants.OP_SUBSCRIBED:
                        handleSubscribed(message);
                        break;

                    case ProtocolOpConstants.OP_UNSUBSCRIBED:
                        //handleUnsubscribed(message);
                        break;

                    case ProtocolOpConstants.OP_EVENT:
                        handleMessage(message);
                        break;

                    case ProtocolOpConstants.OP_ERROR:
                        //handleError(message);
                        break;

                    case ProtocolOpConstants.OP_GOODBYE:
                        //handleGoodbye(message);
                        break;

                    case ProtocolOpConstants.OP_ACK:
                        // handleAck(message);
                        break;

                    case ProtocolOpConstants.OP_MAP_RESPONSE:
                        // handleMapResponse(message);
                        break;
                    }
                }
            }
        }
Beispiel #4
0
        protected override void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            String json = e.Data;

            if (json.Contains("/scan"))
            {
                json = json.Replace("null", "\"Infinity\"");
            }

            JObject operation = JsonConvert.DeserializeObject <JObject>(json);

            //Debug.Log(json);
            switch (operation.GetOperation())
            {
            case "publish":
            {
                receivedPublish(operation, e.RawData);
                return;
            }

            case "service_response":
            {
                //receivedServiceResponse(operation, e.RawData);
                return;
            }

            case "call_service":
            {
                //receivedServiceCall(operation, e.RawData);
                return;
            }
            }
        }
Beispiel #5
0
 public static void handleWebSocket(object session, WebSocketMessageEventArgs msg)
 {
     //没有启用插件
     if (!Main.mainData.getEnable())
     {
         return;
     }
 }
        private void OnMessageReceived(object sender, WebSocketMessageEventArgs args)
        {
            var app = _applications.GetApplicationByHost(args.Connection.Host);

            if (app != null)
            {
                app.NotifyMessageReceived(args.Connection, args.Message);
            }
        }
 private void WebSocketNewMessage(HttpServerWebSocketContext context, WebSocketMessageEventArgs args)
 {
     if (context.UserState is WebSocketBinaryState)
     {
         if (args.Opcode == WebSocketOpcode.Binary)
         {
             this.ParseBinary(context, args);
         }
     }
 }
Beispiel #8
0
 private void WebSocketNewMessage(HttpServerWebSocketContext context, WebSocketMessageEventArgs args)
 {
     if (context.UserState is WebSocketJsonState)
     {
         if (args.Opcode == WebSocketOpcode.Text)
         {
             this.ParseText(context, args);
         }
     }
 }
Beispiel #9
0
        /// <summary>
        /// Called when a web socket message as been captured. This will notify others
        /// via the statically available event.
        /// </summary>
        /// <param name="sender">The web socket session that is captured.</param>
        /// <param name="e">The event argument containing the web socket message that was captured.</param>
        private static void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            var handler = WebSocketCaptured;
            var session = sender as Session;
            var message = e == null ? null : e.oWSM;

            if (handler != null && session != null && message != null)
            {
                handler(session, message);
            }
        }
Beispiel #10
0
 private void FiddlerApplicationOnOnWebSocketMessage_(
     object sender,
     WebSocketMessageEventArgs args)
 {
     if (sender is Session session)
     {
         var message = args.oWSM;
         handler_.Enqueue(session, message);
     }
     else
     {
         Log.Info("Unknown sender");
     }
 }
        public override void Start(string url, string sslCertificateSerialNumber)
        {
            _webSocketServer = new WebSocketServer(url);

            if (sslCertificateSerialNumber != null)
            {
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certificate = store.Certificates
                    .Find(X509FindType.FindBySerialNumber, sslCertificateSerialNumber, false)
                    .OfType<X509Certificate2>()
                    .FirstOrDefault();

                _webSocketServer.Certificate = certificate;
            }

            _logger.Info("Starting WebSocket server");
            _webSocketServer.Start(c =>
            {
                c.OnOpen = () =>
                    {
                        _logger.Debug("Opened connection: " + c.ConnectionInfo.Id);
                        RegisterConnection(new FleckWebSocketConnection(c));
                    };
                c.OnClose = () =>
                    {
                        _logger.Debug("Closed connection: " + c.ConnectionInfo.Id);
                        UnregisterConnection(c.ConnectionInfo.Id);
                    };
                
                c.OnMessage = msg =>
                    {
                        _logger.Debug("Received message for connection: " + c.ConnectionInfo.Id);

                        var fc = WaitConnection(c.ConnectionInfo.Id);
                        if (fc == null)
                        {
                            _logger.ErrorFormat("Connection {0} is not registered", c.ConnectionInfo.Id);
                            return;
                        }

                        var e = new WebSocketMessageEventArgs(fc, msg);
                        OnMessageReceived(e);
                    };
            });
        }
Beispiel #12
0
 /// <summary>
 /// Handles the <see cref="IWebSocket.MessageReceived"/> event; triggering any associated events.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="WebSocketMessageEventArgs"/> instance containing the event data.</param>
 private void WebSocket_MessageReceived(object sender, WebSocketMessageEventArgs e)
 {
     try
     {
         this.EventRouter.RouteAsync(this, e)
         .ConfigureAwait(false);
     }
     catch (ActionInvokeException ex)
     {
         // attempt to invoke the error with a context
         this.Error?.Invoke(this, new StreamDeckClientErrorEventArgs(ex.InnerException, e.Message, ex.Context));
     }
     catch (Exception ex)
     {
         // otherwise simply invoke the error
         this.Error?.Invoke(this, new StreamDeckClientErrorEventArgs(ex, e?.Message));
     }
 }
        protected override void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            Debug.LogFormat("Web socket {1} message:\n{0}", e.Data, e.IsBinary ? "binary" : "string");

            // Update watermark id
            var match = Regex.Match(e.Data, "\"watermark\":\\s?\"([A-z0-9])\"", RegexOptions.Multiline);

            if (match.Groups.Count == 2)
            {
                Watermark = match.Groups[1].Value;
                Debug.Log("Watermark id:" + Watermark);
            }

            // Raise web socket data handler event
            if (OnData != null)
            {
                OnData(e.RawData, e.Data, e.IsBinary);
            }
        }
Beispiel #14
0
        protected override void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            Debug.LogFormat("Web socket {1} message:\n{0}", e.Data, e.IsBinary ? "binary" : "string");

            // Renew activity timer
            ResetIdleTimer();

            // Only process text messages
            if (string.IsNullOrEmpty(e.Data))
            {
                return;
            }

            // Handle "turn.end" message as a new request id will be need to be generated!
            var match = Regex.Match(e.Data, "^Path:([A-z\\.]+)", RegexOptions.Multiline);

            if (match.Groups.Count == 2 && match.Groups[1].Value.Equals("turn.end"))
            {
                NewTurn();
            }
            else if (match.Groups.Count == 2 && match.Groups[1].Value.Equals("speech.phrase"))
            {
                // If a LUIS app script is attached then hand-off "speech.phrase" message as LUIS query request
                if (luisApp != null)
                {
                    string       jsonBody = e.Data.Substring(e.Data.IndexOf("{"));
                    SpeechPhrase phrase   = SpeechMessageHandler.ParseSpeechPhrase(jsonBody);
                    if (!string.IsNullOrEmpty(phrase.DisplayText))
                    {
                        Debug.Log("Send phrase to LUIS app: " + phrase.DisplayText);
                        luisApp.AddQueryToQueue(phrase.DisplayText);
                    }
                }
            }

            // Raise web socket data handler event
            if (OnData != null)
            {
                OnData(e.RawData, e.Data, e.IsBinary);
            }
        }
Beispiel #15
0
        static void Message(HttpServerWebSocketContext context, WebSocketMessageEventArgs e)
        {
            if (e.Opcode == WebSocketOpcode.Text)
            {
                Console.WriteLine("S Receive: {0} Say {1}", context.UserState, e.Message);

                if (e.Message == "说:16")
                {
                    context.Send(string.Format("Receive:{0}, Closed", e.Message));
                    //停止
                    context.Close();
                }
                else
                {
                    context.Send(string.Format(context.UserState + " Say {0}", e.Message));
                }
            }
            else
            {
                Console.WriteLine("{0} Opcode:{1}", context.UserState, e.Opcode);
            }
        }
        void _onEventNotificationMessage(object sender, WebSocketMessageEventArgs e)
        {
            if (e.Message.DtoGuid == DtoGuid)
            {
                Debug.WriteLine($"ProxyBase: Event {e.Message.MemberName} notified on {this} with value {e.Message.Response}");
                if (e.Message.MemberName == nameof(INotifyPropertyChanged.PropertyChanged))
                {
                    PropertyChangedWithValueEventArgs eav = e.Message.Response as PropertyChangedWithValueEventArgs;
                    if (eav != null)
                    {
                        Type         type     = this.GetType();
                        PropertyInfo property =
                            type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).FirstOrDefault(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), true).Where(a => ((JsonPropertyAttribute)a).PropertyName == eav.PropertyName).Any());
                        if (property != null)
                        {
                            Debug.WriteLine(property.Name);
                        }
                        if (property == null)
                        {
                            property = type.GetProperty(eav.PropertyName);
                        }
//                        if (property.Name == "Commands")
//                            Debug.WriteLine(property.Name);
                        object value = eav.Value;
                        if (property != null)
                        {
                            MethodParametersAlignment.AlignType(ref value, property.PropertyType);
                        }
                        Properties[eav.PropertyName] = value;
                        NotifyPropertyChanged(eav.PropertyName);
                    }
                }
                else
                {
                    OnEventNotification(e.Message);
                }
            }
        }
Beispiel #17
0
        public override void Start(string url, string sslCertificateSerialNumber)
        {
            _webSocketServer = new WebSocketServer(url);

            if (sslCertificateSerialNumber != null)
            {
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certificate = store.Certificates
                                  .Find(X509FindType.FindBySerialNumber, sslCertificateSerialNumber, false)
                                  .OfType <X509Certificate2>()
                                  .FirstOrDefault();

                _webSocketServer.Certificate = certificate;
            }

            _webSocketServer.Start(c =>
            {
                c.OnOpen  = () => RegisterConnection(new FleckWebSocketConnection(c));
                c.OnClose = () => UnregisterConnection(c.ConnectionInfo.Id);

                c.OnMessage = msg =>
                {
                    var fc = GetConnection(c.ConnectionInfo.Id);
                    if (fc == null)
                    {
                        LogManager.GetLogger(GetType())
                        .ErrorFormat("Connection {0} isn't registered", c.ConnectionInfo.Id);
                        return;
                    }

                    var e = new WebSocketMessageEventArgs(fc, msg);
                    OnMessageReceived(e);
                };
            });
        }
Beispiel #18
0
        private void ParseText(HttpServerWebSocketContext context, WebSocketMessageEventArgs args)
        {
            Hashtable table = Adf.JsonHelper.DeserializeBase(args.Message) as Hashtable;

            //
            if (table == null)
            {
                Program.LogManager.Warning.WriteTimeLine("receive a empty packet from " + context.GetRemoteNode());
                return;
            }
            //
            string action = table["action"] as string;
            string queue  = table["queue"] as string;
            string id     = table["requestid"] as string;

            //
            if (queue == null)
            {
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, no set queue from " + context.GetRemoteNode());
            }
            else if (id == null || id == "")
            {
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, no set id from " + context.GetRemoteNode());
            }
            else if (action == "pull")
            {
                this.Pull(context, queue, id);
            }
            else if (action == "lpush")
            {
                string body = table["body"] as string;

                this.LPush(context, queue, id, body);
            }
            else if (action == "rpush")
            {
                string body = table["body"] as string;

                this.RPush(context, queue, id, body);
            }
            else if (action == "delete")
            {
                this.Delete(context, queue, id);
            }
            else if (action == "lcancel")
            {
                this.LCancel(context, queue, id);
            }
            else if (action == "rcancel")
            {
                this.RCancel(context, queue, id);
            }
            else if (action == "clear")
            {
                this.Clear(context, queue, id);
            }
            else if (action == "count")
            {
                this.Count(context, queue, id);
            }
            else if (action == "createqueue")
            {
                this.CreateQueue(context, queue, id);
            }
            else if (action == "deletequeue")
            {
                this.DeleteQueue(context, queue, id);
            }
            else
            {
                //ignore
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, unknown action " + action + " from " + context.GetRemoteNode());
            }
        }
Beispiel #19
0
        private void WebSocketNewMessage(HttpServerWebSocketContext context, WebSocketMessageEventArgs args)
        {
            var state = context.UserState as ConnectionState;

            if (state == null)
            {
                return;
            }

            if (args.Opcode == WebSocketOpcode.Text)
            {
                var messageItems = args.Message.Split(':');
                if (messageItems[0] == "elect" && messageItems.Length == 3)
                {
                    //req ,    elect:xxxxx:masterkey
                    //resp,    elect:xxxxx:num
                    var num = HAContext.GetMasterNum();
                    if (num == 0)
                    {
                        var masterKey   = messageItems[2];
                        var disabledNum = 0;
                        if (state.num == 1 && HAContext.MasterKey != masterKey)
                        {
                            disabledNum = 1;
                        }
                        else if (state.num == 2 && HAContext.MasterKey != masterKey)
                        {
                            disabledNum = 2;
                        }
                        //
                        num = HAContext.Elect(disabledNum);
                    }
                    //
                    if (num == 1 || num == 2 || num == 3)
                    {
                        this.logManager.Message.WriteTimeLine("HAServer response elect node " + num + " to " + state.ip);

                        try
                        {
                            context.SendAsync("elect:" + messageItems[1] + ":" + num, null);
                        }
                        catch (System.IO.IOException) { }
                        catch (System.Net.Sockets.SocketException) { }
                        catch (System.Exception)
                        {
                        }
                    }
                    //else
                    //{
                    //    //discard message
                    //}
                }
                else if (messageItems[0] == "readmasterkey")
                {
                    this.logManager.Message.WriteTimeLine("HAServer send master key " + HAContext.MasterKey + " to " + state.ip);
                    //
                    try
                    {
                        context.SendAsync("masterkey:" + HAContext.MasterKey, null);
                    }
                    catch (System.IO.IOException) { }
                    catch (System.Net.Sockets.SocketException) { }
                    catch (System.Exception)
                    {
                    }
                }
            }
        }
        private void Message(object sender, WebSocketMessageEventArgs e)
        {
            if (e.Opcode == WebSocketOpcode.Text)
            {
                this.receiveCounter++;

                var table  = Adf.JsonHelper.Deserialize <Hashtable>(e.Message);
                var queue  = table["queue"] as string;
                var action = table["action"] as string;

                if (action == "rpush")
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} push ack, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          );
                        Console.WriteLine("input pull");
                    }
                    else if (this.receiveCounter % 10000 == 0)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                else if (action == "pull")
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} pull ack, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          );
                        Console.WriteLine("input delete");
                    }
                    else if (this.receiveCounter % 10000 == 0)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                else if (action == "delete")
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} delete ack, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          );
                        Console.WriteLine("input end to end");
                    }
                    else if (this.receiveCounter % 10000 == 0)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                else
                {
                    Console.WriteLine(e.Message);
                }

                //if (e.Message == END)
                //{
                //    Console.WriteLine("recv {0} completed, seconds:{1}, {2} loop/s"
                //        , SIZE
                //        , (double)(stopwatch.ElapsedMilliseconds / 1000)
                //        , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                //        );
                //}
            }
        }
Beispiel #21
0
        static void Message(HttpServerWebSocketContext context, WebSocketMessageEventArgs e)
        {
            //Console.WriteLine("Receive {0} Opcode:{1}", context.UserState, e.Opcode);

            //if (e.Opcode == WebSocketOpcode.Text)
            //{
            //if (e.Message == "1")
            //{
            //    Console.WriteLine("New Received");

            //    System.Threading.ThreadPool.QueueUserWorkItem(a =>
            //    {
            //        while (true)
            //        {
            //            if (context.Socket.Connected == false)
            //            {
            //                break;
            //            }

            //            try
            //            {
            //                context.Send(new byte[1024]);
            //            }
            //            catch
            //            {
            //                Console.WriteLine("Response but closed");
            //            }
            //        }

            //        Console.WriteLine("Response but disconnection");
            //        Console.WriteLine();

            //    });
            //}
            //}

            //System.Threading.ThreadPool.QueueUserWorkItem(us =>
            //{

            var index = System.Threading.Interlocked.Increment(ref di);

            try
            {
                //context.Send(datas[index % 4]);
                //context.Send(new byte[1024]);

                if (e.Opcode == WebSocketOpcode.Text)
                {
                    Console.WriteLine("Recv: " + e.Message);

                    context.Send("Msg:" + index);
                }
                else if (e.Opcode == WebSocketOpcode.Binary)
                {
                    Console.WriteLine("Recv a binary: " + e.Message);
                }
                else
                {
                    Console.WriteLine("Recv: " + e.Opcode);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Response err: " + exception.Message);
            }

            //});
        }
Beispiel #22
0
        private void Message(object sender, WebSocketMessageEventArgs e)
        {
            if (e.Opcode == WebSocketOpcode.Binary)
            {
                this.receiveCounter++;

                var result = Adf.QueueServerEncoder.Decode(e.Buffer);

                //var table = Adf.JsonHelper.Deserialize<Hashtable>(e.Message);
                //var queue = table["queue"] as string;
                //var action = table["action"] as string;

                if (result.Action == QueueServerAction.RPUSH)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} rpush ack,success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess);
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                }
                else if (result.Action == QueueServerAction.LPUSH)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} lpush ack,success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess);
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                }
                else if (result.Action == QueueServerAction.PULL)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} pull ack, success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess
                                          );
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                    else
                    {
                        Console.WriteLine(result.GetBodyString());
                    }
                }
                else if (result.Action == QueueServerAction.DELETE)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} delete ack, success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess
                                          );
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                }
                else if (result.Action == QueueServerAction.COUNT)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} count ack, success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess
                                          );
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                }
                else if (result.Action == QueueServerAction.CLEAR)
                {
                    if (this.receiveCounter == SIZE)
                    {
                        Console.WriteLine("recv {0} clear ack, success:{3}, seconds:{1}, {2} loop/s"
                                          , SIZE
                                          , (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                                          , this.resultSuccess
                                          );
                        Console.WriteLine("input cq/dq/rpush/lpush/pull/delete/clear/count/end");
                    }
                    //else if (this.receiveCounter % 10000 == 0)
                    //{
                    //    Console.WriteLine(e.Message);
                    //}
                }
                else
                {
                    Console.WriteLine(e.Message);
                }

                //
                if (result.Result == QueueServerAction.OK)
                {
                    this.resultSuccess++;
                }
                else
                {
                    Console.WriteLine(result.Result);
                }

                //if (e.Message == END)
                //{
                //    Console.WriteLine("recv {0} completed, seconds:{1}, {2} loop/s"
                //        , SIZE
                //        , (double)(stopwatch.ElapsedMilliseconds / 1000)
                //        , SIZE / (double)(stopwatch.ElapsedMilliseconds / 1000)
                //        );
                //}
            }
        }
 private async Task VoiceWS_SocketMessage(WebSocketMessageEventArgs e)
 {
     await this.HandleDispatch(JObject.Parse(e.Message));
 }
Beispiel #24
0
        public override void Start(string url, string sslCertificateSerialNumber)
        {
            var uri       = new Uri(url);
            var listenUrl = string.Format("{0}://0.0.0.0:{1}", uri.Scheme, uri.Port);

            _webSocketServer = new WebSocketServer(listenUrl);

            if (sslCertificateSerialNumber != null)
            {
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certificate = store.Certificates
                                  .Find(X509FindType.FindBySerialNumber, sslCertificateSerialNumber, false)
                                  .OfType <X509Certificate2>()
                                  .FirstOrDefault();

                _webSocketServer.Certificate = certificate;
            }

            _logger.Info("Starting WebSocket server");
            _webSocketServer.Start(c =>
            {
                c.OnOpen = () =>
                {
                    _logger.Debug("Opened connection: " + c.ConnectionInfo.Id);
                    RegisterConnection(new FleckWebSocketConnection(c));
                };
                c.OnClose = () =>
                {
                    _logger.Debug("Closed connection: " + c.ConnectionInfo.Id);
                    UnregisterConnection(c.ConnectionInfo.Id);
                };

                c.OnMessage = msg =>
                {
                    _logger.Debug("Received message for connection: " + c.ConnectionInfo.Id);

                    var fc = WaitConnection(c.ConnectionInfo.Id);
                    if (fc == null)
                    {
                        _logger.ErrorFormat("Connection {0} is not registered", c.ConnectionInfo.Id);
                        return;
                    }

                    var e = new WebSocketMessageEventArgs(fc, msg);
                    OnMessageReceived(e);
                };

                c.OnPing = data =>
                {
                    _logger.Debug("Received ping for connection: " + c.ConnectionInfo.Id);

                    var fc = WaitConnection(c.ConnectionInfo.Id);
                    if (fc == null)
                    {
                        _logger.ErrorFormat("Connection {0} is not registered", c.ConnectionInfo.Id);
                        return;
                    }

                    var e = new WebSocketConnectionEventArgs(fc);
                    OnPingReceived(e);

                    c.SendPong(data);
                };
            });
        }
        private void ParseBinary(HttpServerWebSocketContext context, WebSocketMessageEventArgs args)
        {
            var buffer       = args.Buffer;
            var bufferLength = buffer.Length;

            if (bufferLength == 0)
            {
                Program.LogManager.Warning.WriteTimeLine("receive a empty packet from " + context.GetRemoteNode());
                return;
            }

            //struct

            /*
             * action
             * id
             * queue
             *
             */

            int length   = 0;
            int position = 0;

            byte   action = 0;
            string id     = null;
            string queue  = null;

            //action
            action   = buffer[0];
            position = 1;
            //id
            length    = Adf.BaseDataConverter.ToUInt16(buffer, position);
            position += 2;
            id        = System.Text.Encoding.ASCII.GetString(buffer, position, length);
            position += length;
            //queue
            length    = Adf.BaseDataConverter.ToUInt16(buffer, position);
            position += 2;
            queue     = System.Text.Encoding.ASCII.GetString(buffer, position, length);
            position += length;

            //
            if (queue == null)
            {
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, no set queue from " + context.GetRemoteNode());
            }
            else if (id == null || id == "")
            {
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, no set id from " + context.GetRemoteNode());
            }
            else if (action == Action.PULL)
            {
                this.Pull(context, queue, id);
            }
            else if (action == Action.LPUSH)
            {
                length    = Adf.BaseDataConverter.ToUInt16(buffer, position);
                position += 2;
                var body = new byte[length];
                Array.Copy(buffer, position, body, 0, length);
                //position += length;

                this.LPush(context, queue, id, body);
            }
            else if (action == Action.RPUSH)
            {
                length    = Adf.BaseDataConverter.ToUInt16(buffer, position);
                position += 2;
                var body = new byte[length];
                Array.Copy(buffer, position, body, 0, length);
                //position += length;

                this.RPush(context, queue, id, body);
            }
            else if (action == Action.DELETE)
            {
                this.Delete(context, queue, id);
            }
            else if (action == Action.LCANCEL)
            {
                this.LCancel(context, queue, id);
            }
            else if (action == Action.RCANCEL)
            {
                this.RCancel(context, queue, id);
            }
            else if (action == Action.COUNT)
            {
                this.Count(context, queue, id);
            }
            else if (action == Action.CLEAR)
            {
                this.Clear(context, queue, id);
            }
            else if (action == Action.CREATEQUEUE)
            {
                this.CreateQueue(context, queue, id);
            }
            else if (action == Action.DELETEQUEUE)
            {
                this.DeleteQueue(context, queue, id);
            }
            else
            {
                //ignore
                Program.LogManager.Warning.WriteTimeLine("receive a invalid packet, unknown action " + action + " from " + context.GetRemoteNode());
            }
        }
Beispiel #26
0
 private static void OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
 {
 }
Beispiel #27
0
        private void ClientOnMessage(object sender, WebSocketMessageEventArgs e)
        {
            var client = (WebSocketClient)sender;
            var num    = (int)client.UserState;

            //
            if (e.Opcode == WebSocketOpcode.Text)
            {
                var messageItems = e.Message.Split(':');
                if (messageItems[0] == "elect")
                {
                    //req ,    elect:xxxxx:masterkey
                    //resp,    elect:xxxxx:num
                    var electNum = 0;
                    if (messageItems.Length == 3 && messageItems[1] == this.electIdentity && int.TryParse(messageItems[2], out electNum))
                    {
                        lock (this.electLock)
                        {
                            if (electNum == 1)
                            {
                                this.logManager.Message.WriteTimeLine("HAClient request ack node 1 from node {0}", client.UserState);
                                this.elect1++;
                            }
                            else if (electNum == 2)
                            {
                                this.logManager.Message.WriteTimeLine("HAClient request ack node 2 from node {0}", client.UserState);
                                this.elect2++;
                            }
                            else if (electNum == 3)
                            {
                                this.logManager.Message.WriteTimeLine("HAClient request ack node 3 from node {0}", client.UserState);
                                this.elect3++;
                            }
                            //
                            var count = 0;
                            count += HAContext.Connectioned1 ? 1 : 0;
                            count += HAContext.Connectioned2 ? 1 : 0;
                            count += HAContext.Connectioned3 ? 1 : 0;
                            //, ignore num 3
                            if (this.elect1 == 2)
                            {
                                this.taskQueue.Add("elected:1");
                            }
                            else if (this.elect2 == 2)
                            {
                                this.taskQueue.Add("elected:2");
                            }
                            else if (this.elect3 == 2)
                            {
                                this.taskQueue.Add("elected:3");
                            }
                        }
                    }
                }
                else if (messageItems[0] == "masterkey" && messageItems.Length == 2)
                {
                    HAContext.SaveMasterKey(messageItems[1]);
                    this.logManager.Message.WriteTimeLine("HAClient receive masterkey " + messageItems[1] + " from node " + num);
                    this.readMasterKey = false;
                }
            }
        }
Beispiel #28
0
 protected virtual void OnReceivedMessage(WebSocketMessageEventArgs args)
 {
     RaiseReceivedMessage?.Invoke(this, args);
 }
Beispiel #29
0
        private void FiddlerApplication_OnWebSocketMessage(object sender, WebSocketMessageEventArgs e)
        {
            //((Bitmap)((Fiddler.Session)sender).ViewItem.ImageList.Images[34]).Save(@"D:\A1.ico", System.Drawing.Imaging.ImageFormat.Icon);
            Session          oSession         = (Session)sender;
            WebSocketMessage webSocketMessage = e.oWSM;

            if (!isOnLoad)
            {
                return;
            }
            if (webSocketMessage == null)
            {
                AddFiddlerObjectLog("get null WebSocketMessage");
                return;
            }
            if (webSocketMessage.FrameType == WebSocketFrameTypes.Close ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Ping ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Pong ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Reservedx3 ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Reservedx4 ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Reservedx5 ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Reservedx6 ||
                webSocketMessage.FrameType == WebSocketFrameTypes.Reservedx7 ||
                webSocketMessage.FrameType == WebSocketFrameTypes.ReservedxB ||
                webSocketMessage.FrameType == WebSocketFrameTypes.ReservedxC ||
                webSocketMessage.FrameType == WebSocketFrameTypes.ReservedxD ||
                webSocketMessage.FrameType == WebSocketFrameTypes.ReservedxE ||
                webSocketMessage.FrameType == WebSocketFrameTypes.ReservedxF)
            {
                return;
            }
            if ((myFreeHttpWindow.IsRequestRuleEnable && webSocketMessage.IsOutbound) || (myFreeHttpWindow.IsResponseRuleEnable && !webSocketMessage.IsOutbound))
            {
                if (isSkipUiHide && oSession["ui-hide"] == "true")
                {
                    return;
                }
                if (myFreeHttpWindow.ModificSettingInfo.IsSkipConnectTunnels && oSession.RequestMethod == "CONNECT")
                {
                    return;
                }
                bool isRequest = webSocketMessage.IsOutbound;
                List <IFiddlerHttpTamper> matchItems = null;
                if (isRequest)
                {
                    matchItems = FiddlerSessionHelper.FindMatchTanperRule(oSession, myFreeHttpWindow.FiddlerRequestChangeList, isRequest, webSocketMessage);
                }
                else
                {
                    //oSession.WriteResponseToStream(new MemoryStream(new Byte[] { 0x81,0x81,0x01,0x41 }), false);
                    //WebSocket ws = oSession.__oTunnel as WebSocket;
                    //ws.listMessages.Add(webSocketMessage);
                    matchItems = FiddlerSessionHelper.FindMatchTanperRule(oSession, myFreeHttpWindow.FiddlerResponseChangeList, isRequest, webSocketMessage);
                }
                if (matchItems != null && matchItems.Count > 0)
                {
                    foreach (var matchItem in matchItems)
                    {
                        ListViewItem tempListViewItem = myFreeHttpWindow.FindListViewItemFromRule(matchItem);
                        FreeHttpWindow.MarkMatchRule(tempListViewItem);
                        MarkSession(oSession);
                        ShowMes(string.Format("macth the [requst rule {0}] with {1}", tempListViewItem.SubItems[0].Text, oSession.fullUrl));
                        FiddlerSessionTamper.ModificWebSocketMessage(oSession, webSocketMessage, matchItem, isRequest, ShowError, ShowMes);
                        if (!isRequest)
                        {
                            FiddlerResponseChange nowFiddlerResponseChange = ((FiddlerResponseChange)matchItem);
                            if (nowFiddlerResponseChange.LesponseLatency > 0)
                            {
                                ShowMes(string.Format("[reponse rule {0}] is modified , now delay {1} ms", tempListViewItem.SubItems[0].Text, nowFiddlerResponseChange.LesponseLatency));
                                System.Threading.Thread.Sleep(nowFiddlerResponseChange.LesponseLatency);
                            }
                            if (myFreeHttpWindow.ModificSettingInfo.IsOnlyMatchFistTamperRule)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// プロキシエンジンを指定して初期化
        /// </summary>
        /// <param name="engine">プロキシエンジン</param>
        public HttpProxy(Spi.IReadOnlyHttpProxyEngine engine)
        {
            this.proxyEngine         = engine;
            engine.HttpRequestSent  += (sender, args) => this.HttpRequestSent?.Invoke(sender, ReadOnlyHttpRequestEventArgs.Convert(args));
            engine.HttpResponseSent += (sender, args) => this.HttpResponseSent?.Invoke(sender, ReadOnlySessionEventArgs.Convert(args));
            engine.FatalException   += (sender, args) => this.FatalException?.Invoke(sender, ExceptionEventArgs.Convert(args));

            if (engine is Spi.IHttpProxyEngine writableEngine)
            {
                writableEngine.HttpRequestReceived  += (sender, args) => this.HttpRequestReceived?.Invoke(sender, HttpRequestEventArgs.Convert(args));
                writableEngine.HttpResponseReceived += (sender, args) => this.HttpResponseReceived?.Invoke(sender, SessionEventArgs.Convert(args));
            }
            if (engine is Spi.IReadOnlyWebSocketProxyEngine rowsEngine)
            {
                rowsEngine.ClientWebSocketMessageSent += (sender, args) => this.ClientWebSocketMessageSent?.Invoke(sender, ReadOnlyWebSocketMessageEventArgs.Convert(args));
                rowsEngine.ServerWebSocketMessageSent += (sender, args) => this.ServerWebSocketMessageSent?.Invoke(sender, ReadOnlyWebSocketMessageEventArgs.Convert(args));
            }
            if (engine is Spi.IWebSocketProxyEngine wsEngine)
            {
                wsEngine.ClientWebSocketMessageReceived += (sender, args) => this.ClientWebSocketMessageReceived?.Invoke(sender, WebSocketMessageEventArgs.Convert(args));
                wsEngine.ServerWebSocketMessageReceived += (sender, args) => this.ServerWebSocketMessageReceived?.Invoke(sender, WebSocketMessageEventArgs.Convert(args));
            }
        }