public WebSocketMessageReceivedEventArgs(WebSocketMessage message, IWebSocketClientSession webSocketClientSession)
        {
            if (message == null) throw new ArgumentNullException(nameof(message));
            if (webSocketClientSession == null) throw new ArgumentNullException(nameof(webSocketClientSession));

            Message = message;
            WebSocketClientSession = webSocketClientSession;
        }
Ejemplo n.º 2
0
	private static void OnMessageReceived(object sender,MessageReceivedEventArgs e)
	{
		var client = (WebSocketClient)sender;
		Console.WriteLine("Received by [{0}]",((IPEndPoint)client.Socket.RemoteEndPoint).ToString());

		var received_msg = Encoding.UTF8.GetString(e.DecodedMessage);
		Console.WriteLine("Received message: {0}",received_msg);
		
		var msg = new WebSocketMessage();
		msg.Append(received_msg);

		client.SendMessage(msg);
	}
Ejemplo n.º 3
0
 public static byte[] DecodeMask(WebSocketMessage oWSM)
 {
     byte[] payloadData;
     if (oWSM.MaskingKey == null)
     {
         payloadData = oWSM.PayloadData;
     }
     else
     {
         byte[] MaskingKey = oWSM.MaskingKey;
         int    maskLen    = (int)MaskingKey.Length;
         byte[] payload    = oWSM.PayloadData;
         byte[] s          = new byte[oWSM.PayloadLength];
         int    i          = 0;
         for (int j = 0; j < (int)payload.Length; j++)
         {
             int num = i;
             i    = num + 1;
             s[j] = (byte)(payload[j] ^ MaskingKey[num % maskLen]);
         }
         payloadData = s.ToArray <byte>(0);
     }
     return(payloadData);
 }
Ejemplo n.º 4
0
        public IHttpActionResult UpdateSwitch(SwitchViewModel model)
        {
            var result = _switchService.UpdateSwitch(User.Identity.GetUserId(), model);

            var client = LynexWebSocketHandler.GetWebSocketSession(model.SiteId);

            if (client != null)
            {
                var list             = _switchService.GetSwitchesAndSchedule(User.Identity.GetUserId(), model.SiteId);
                var webSocketMessage = new WebSocketMessage(WebSocketMessageType.PiSiteStatus);
                webSocketMessage.BroadcastType = WebSocketBroadcastType.Pi;
                webSocketMessage.Message       = list;
                client.SendToPi(JsonConvert.SerializeObject(webSocketMessage));
            }

            var obj = new
            {
                Success = true,
                Message = "",
                Results = result,
            };

            return(Ok(obj));
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            WebSocketServer server = new WebSocketServer();

            server.OnConnect += (src) => {
                Console.WriteLine("Someone connected! IP: " + ((IPEndPoint)src.Socket.LocalEndPoint).Address.MapToIPv4());

                var message = new WebSocketMessage("try");
                message.Content["test"] = 123;

                server.SendMessage(src, message);
            };

            server.OnDisconnect += (src) => {
                Console.WriteLine("Someone disconnected! IP: " + ((IPEndPoint)src.Socket.LocalEndPoint).Address.MapToIPv4());
            };

            server.On["test"] = (src, e) => {
                Console.WriteLine("test send:");
                Console.WriteLine(e.Message.Content["name"]);
            };

            server.Start();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Implementation of the OnMessage event
        /// </summary>
        /// <param name="e"></param>
        private void OnMessageImpl(WebSocketMessage webSocketMessage)
        {
            var e = (WebSocketClientWrapper.TextMessage)webSocketMessage.Data;

            try
            {
                var token = JToken.Parse(e.Message);

                if (token is JArray)
                {
                    var channel = token[0].ToObject <int>();

                    // heartbeat
                    if (token[1].Type == JTokenType.String && token[1].Value <string>() == "hb")
                    {
                        return;
                    }

                    // account information channel
                    if (channel == 0)
                    {
                        var term = token[1].ToObject <string>();
                        switch (term.ToLowerInvariant())
                        {
                        // order closed
                        case "oc":
                            OnOrderClose(token[2].ToObject <Messages.Order>());
                            return;

                        // trade execution update
                        case "tu":
                            EmitFillOrder(token[2].ToObject <TradeExecutionUpdate>());
                            return;

                        // notification
                        case "n":
                            var notification = token[2];
                            var status       = notification[6].ToString();

                            if (status == "ERROR")
                            {
                                var errorMessage = notification[7].ToString();
                                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, $"Error: {errorMessage}"));

                                OnOrderError(notification[4].ToObject <Messages.Order>());
                            }
                            else if (status == "SUCCESS")
                            {
                                var type = notification[1].ToString();

                                if (type == "on-req")
                                {
                                    OnOrderNew(notification[4].ToObject <Messages.Order>());
                                }
                                else if (type == "ou-req")
                                {
                                    OnOrderUpdate(notification[4].ToObject <Messages.Order>());
                                }
                            }
                            return;

                        default:
                            return;
                        }
                    }
                }
                else if (token is JObject)
                {
                    var raw = token.ToObject <BaseMessage>();
                    switch (raw.Event.ToLowerInvariant())
                    {
                    case "auth":
                        var auth   = token.ToObject <AuthResponseMessage>();
                        var result = string.Equals(auth.Status, "OK", StringComparison.OrdinalIgnoreCase) ? "successful" : "failed";
                        Log.Trace($"BitfinexBrokerage.OnMessage: Subscribing to authenticated channels {result}");
                        return;

                    case "info":
                    case "ping":
                        return;

                    case "error":
                        var error = token.ToObject <ErrorMessage>();
                        Log.Error($"BitfinexBrokerage.OnMessage: {error.Level}: {error.Message}");
                        return;

                    default:
                        Log.Error($"BitfinexBrokerage.OnMessage: Unexpected message format: {e.Message}");
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
                throw;
            }
        }
Ejemplo n.º 7
0
        public virtual async void ReadResponses(object param)
        {
            while (true)
            {
                try
                {
                    string resp = "";
                    WebSocketReceiveResult webSocketResp;
                    if (SubscriptionWebSocket.State == WebSocketState.Open)
                    {
                        do
                        {
                            ArraySegment <byte> bytesReceived = new ArraySegment <byte>(new byte[1000]);
                            webSocketResp = await SubscriptionWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None);

                            resp += Encoding.ASCII.GetString(bytesReceived.Array, 0, webSocketResp.Count);
                        }while (!webSocketResp.EndOfMessage);

                        if (resp != "")
                        {
                            WebSocketMessage wsResp = JsonConvert.DeserializeObject <WebSocketMessage>(resp);

                            if (wsResp.Msg == "ClientLoginResponse")
                            {
                                ClientLoginResponse loginReponse = JsonConvert.DeserializeObject <ClientLoginResponse>(resp);
                                OnEvent(loginReponse);
                            }
                            else if (wsResp.Msg == "ClientReject")
                            {
                                ClientReject loginRejected = JsonConvert.DeserializeObject <ClientReject>(resp);
                                OnEvent(loginRejected);
                            }
                            else if (wsResp.Msg == "ClientLogoutResponse")
                            {
                                ClientLogoutResponse logoutReponse = JsonConvert.DeserializeObject <ClientLogoutResponse>(resp);
                                OnEvent(logoutReponse);
                            }
                            else if (wsResp.Msg == "SubscriptionResponse")
                            {
                                SubscriptionResponse subscrResponse = JsonConvert.DeserializeObject <SubscriptionResponse>(resp);
                                OnEvent(subscrResponse);
                            }
                            else if (wsResp.Msg == "ClientHeartbeatRequest")
                            {
                                OnEvent(JsonConvert.DeserializeObject <ClientHeartbeat>(resp));
                            }
                            else if (wsResp.Msg == "AccountRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <AccountRecord>(resp));
                            }
                            else if (wsResp.Msg == "CreditRecordUpdate")
                            {
                                OnEvent(JsonConvert.DeserializeObject <CreditRecordUpdate>(resp));
                            }
                            else if (wsResp.Msg == "DailySettlementPrice")
                            {
                                OnEvent(JsonConvert.DeserializeObject <DailySettlementPrice>(resp));
                            }
                            else if (wsResp.Msg == "FirmRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <FirmRecord>(resp));
                            }
                            else if (wsResp.Msg == "OfficialFixingPrice")
                            {
                                OnEvent(JsonConvert.DeserializeObject <OfficialFixingPrice>(resp));
                            }
                            else if (wsResp.Msg == "RefereceRateMsg")
                            {
                                OnEvent(JsonConvert.DeserializeObject <RefereceRateMsg>(resp));
                            }
                            else if (wsResp.Msg == "SecurityMasterRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <SecurityMasterRecord>(resp));
                            }
                            else if (wsResp.Msg == "UserRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <UserRecord>(resp));
                            }
                            else if (wsResp.Msg == "CreditRecordUpdate")
                            {
                                OnEvent(JsonConvert.DeserializeObject <CreditRecordUpdate>(resp));
                            }
                            else if (wsResp.Msg == "LastSale")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LastSale>(resp));
                            }
                            else if (wsResp.Msg == "Quote")
                            {
                                OnEvent(JsonConvert.DeserializeObject <Quote>(resp));
                            }
                            else if (wsResp.Msg == "DepthOfBook")
                            {
                                OnEvent(JsonConvert.DeserializeObject <DepthOfBook>(resp));
                            }
                            else if (wsResp.Msg == "LegacyOrderAck")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LegacyOrderAck>(resp));
                            }
                            else if (wsResp.Msg == "LegacyOrderCancelRejAck")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LegacyOrderCancelRejAck>(resp));
                            }
                            else
                            {
                                UnknownMessage unknownMsg = new UnknownMessage()
                                {
                                    Msg    = "UnknownMsg",
                                    Resp   = resp,
                                    Reason = string.Format("Unknown message: {0}", resp)
                                };
                                OnEvent(unknownMsg);
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch (Exception ex)
                {
                    ErrorMessage errorMsg = new ErrorMessage()
                    {
                        Msg = "ErrorMsg", Error = ex.Message
                    };
                    OnEvent(errorMsg);
                }
            }
        }
Ejemplo n.º 8
0
        private void OnMessage(object sender, WebSocketMessage e)
        {
            var webSocket = (BitfinexWebSocketWrapper)sender;

            try
            {
                var token = JToken.Parse(e.Message);

                if (token is JArray)
                {
                    var channel = token[0].ToObject <int>();
                    // heartbeat
                    if (token[1].Type == JTokenType.String && token[1].Value <string>() == "hb")
                    {
                        webSocket.ConnectionHandler.KeepAlive(DateTime.UtcNow);
                        return;
                    }

                    // public channels
                    if (channel != 0)
                    {
                        webSocket.ConnectionHandler.KeepAlive(DateTime.UtcNow);

                        if (token.Count() == 2)
                        {
                            OnSnapshot(
                                webSocket,
                                token[0].ToObject <string>(),
                                token[1].ToObject <string[][]>()
                                );
                        }
                        else
                        {
                            // pass channel id as separate arg
                            OnUpdate(
                                webSocket,
                                token[0].ToObject <string>(),
                                token.ToObject <string[]>().Skip(1).ToArray()
                                );
                        }
                    }
                }
                else if (token is JObject)
                {
                    var raw = token.ToObject <Messages.BaseMessage>();
                    switch (raw.Event.ToLowerInvariant())
                    {
                    case "subscribed":
                        OnSubscribe(webSocket, token.ToObject <Messages.ChannelSubscription>());
                        return;

                    case "unsubscribed":
                        OnUnsubscribe(webSocket, token.ToObject <Messages.ChannelUnsubscribing>());
                        return;

                    case "auth":
                    case "info":
                    case "ping":
                        return;

                    case "error":
                        Log.Error($"BitfinexSubscriptionManager.OnMessage(): {e.Message}");
                        return;

                    default:
                        Log.Trace($"BitfinexSubscriptionManager.OnMessage(): Unexpected message format: {e.Message}");
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                _brokerage.OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
                throw;
            }
        }
        public async Task Handle(IAppSession session, WebSocketPackage package)
        {
            var websocketSession = session as WebSocketSession;

            if (package.OpCode == OpCode.Handshake)
            {
                websocketSession.HttpHeader = package.HttpHeader;

                // handshake failure
                if (!(await HandleHandshake(websocketSession, package)))
                {
                    websocketSession.CloseWithoutHandshake();
                    return;
                }

                websocketSession.Handshaked = true;

                var subProtocol = package.HttpHeader.Items["Sec-WebSocket-Protocol"];

                if (!string.IsNullOrEmpty(subProtocol))
                {
                    var subProtocols = subProtocol.Split(',');

                    for (var i = 0; i < subProtocols.Length; i++)
                    {
                        subProtocols[i] = subProtocols[i].Trim();
                    }

                    var subProtocolSelector = _subProtocolSelector;

                    if (subProtocolSelector != null)
                    {
                        var subProtocolSelected = await subProtocolSelector.Select(subProtocols, package.HttpHeader);

                        if (!string.IsNullOrEmpty(subProtocolSelected))
                        {
                            websocketSession.SubProtocol = subProtocolSelected;
                        }
                    }
                }

                await(session.Server as WebSocketService).OnSessionHandshakeCompleted(websocketSession);
                return;
            }


            if (!websocketSession.Handshaked)
            {
                // not pass handshake but receive data package now
                // impossible routine
                return;
            }

            if (package.OpCode == OpCode.Close)
            {
                if (websocketSession.CloseStatus == null)
                {
                    var closeStatus = GetCloseStatusFromPackage(package);

                    websocketSession.CloseStatus = closeStatus;

                    var message = new WebSocketMessage();

                    message.OpCode = OpCode.Close;
                    message.Data   = package.Data;

                    try
                    {
                        await websocketSession.SendAsync(message);
                    }
                    catch (InvalidOperationException)
                    {
                        // support the case the client close the connection right after it send the close handshake
                    }
                }
                else
                {
                    websocketSession.CloseWithoutHandshake();
                }

                return;
            }
            else if (package.OpCode == OpCode.Ping)
            {
                var message = new WebSocketMessage();

                message.OpCode = OpCode.Pong;
                message.Data   = package.Data;

                await websocketSession.SendAsync(message);

                return;
            }

            // application command
            var websocketCommandMiddleware = _websocketCommandMiddleware;

            if (websocketCommandMiddleware != null)
            {
                await websocketCommandMiddleware.Handle(session, package);

                return;
            }

            var packageHandleDelegate = _packageHandlerDelegate;

            if (packageHandleDelegate != null)
            {
                await packageHandleDelegate(websocketSession, package);
            }
        }
Ejemplo n.º 10
0
 public Task Handle(ModelA model, WebSocketMessage message, IHorseWebSocket client)
 {
     Console.WriteLine("Model A received: " + model.Value);
     return(Task.CompletedTask);
 }
Ejemplo n.º 11
0
 protected override void OnEventNotification(WebSocketMessage message)
 {
 }
Ejemplo n.º 12
0
 public void AssignMessage(WebSocketMessage oWSM)
 {
     jsonResponseViewer.AssignMessage(oWSM);
 }
 public void OnWebSocketMessage(WebSocketMessage message) => OnWebSocketMessageDelegate?.Invoke(message);
Ejemplo n.º 14
0
 private static WebSocketMessage[] _ParseMessagesFromStream(WebSocket wsOwner, ref MemoryStream strmData, bool bIsOutbound, bool bTrimAfterParsing)
 {
     List<WebSocketMessage> list = new List<WebSocketMessage>();
     strmData.Position = 0L;
     long position = 0L;
     while ((strmData.Length - strmData.Position) > 2L)
     {
         byte[] buffer = new byte[2];
         strmData.Read(buffer, 0, buffer.Length);
         ulong num2 = (ulong) (buffer[1] & 0x7f);
         if (num2 == 0x7eL)
         {
             if (strmData.Length < (strmData.Position + 2L))
             {
                 break;
             }
             byte[] buffer2 = new byte[2];
             strmData.Read(buffer2, 0, buffer2.Length);
             num2 = (ulong) ((buffer2[0] << 8) + buffer2[1]);
         }
         else if (num2 == 0x7fL)
         {
             if (strmData.Length < (strmData.Position + 8L))
             {
                 break;
             }
             byte[] buffer3 = new byte[8];
             strmData.Read(buffer3, 0, buffer3.Length);
             num2 = (ulong) ((((((((buffer3[0] << 0x18) + (buffer3[1] << 0x10)) + (buffer3[2] << 8)) + buffer3[3]) + (buffer3[4] << 0x18)) + (buffer3[5] << 0x10)) + (buffer3[6] << 8)) + buffer3[7]);
         }
         bool flag = 0x80 == (buffer[1] & 0x80);
         if (strmData.Length < (( strmData.Position + (long)num2) + (flag ?  4L : 0L))
     )                {
             break;
         }
         WebSocketMessage item = new WebSocketMessage(wsOwner, Interlocked.Increment(ref wsOwner._iMsgCount), bIsOutbound);
         item.AssignHeader(buffer[0]);
         if (flag)
         {
             byte[] buffer4 = new byte[4];
             strmData.Read(buffer4, 0, buffer4.Length);
             item.MaskingKey = buffer4;
         }
         byte[] buffer5 = new byte[num2];
         strmData.Read(buffer5, 0, buffer5.Length);
         item.PayloadData = buffer5;
         list.Add(item);
         position = strmData.Position;
     }
     strmData.Position = position;
     if (bTrimAfterParsing)
     {
         byte[] buffer6 = new byte[strmData.Length - position];
         strmData.Read(buffer6, 0, buffer6.Length);
         strmData.Dispose();
         strmData = new MemoryStream();
         strmData.Write(buffer6, 0, buffer6.Length);
     }
     return list.ToArray();
 }
Ejemplo n.º 15
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;
                            }
                        }
                    }
                }
            }
        }
        /*public  WebSocketRequestMessage readRequest(ulong timeoutMillis)
        {
            if (client == null)
            {
                throw new Exception("Connection closed!");
            }

            ulong startTime = KeyHelper.getTime();

            while (client != null && incomingRequests.Count == 0 && elapsedTime(startTime) < timeoutMillis)
            {
                //Util.wait(this, Math.Max(1, timeoutMillis - elapsedTime(startTime)));
            }

            if (incomingRequests.Count == 0 && client == null) throw new Exception("Connection closed!");
            else if (incomingRequests.Count == 0) throw new TimeoutException("Timeout exceeded");
            else
            {
                WebSocketRequestMessage message = incomingRequests.First();
                incomingRequests.RemoveFirst();
                return message;
            }
        }*/

        public async void sendMessage(WebSocketMessage message)
        {
            if (socket == null)
            {
                throw new Exception("Connection closed!");
            }

            messageWriter.WriteBytes(message.ToByteArray());
            await messageWriter.StoreAsync();
        }
 public WebSocketMessageEventArgs(WebSocketMessage _inMsg)
 {
     this.oWSM = _inMsg;
 }
Ejemplo n.º 18
0
        /// <summary>
        ///  Modific the websocket message with your rule
        /// </summary>
        /// <param name="oSession"></param>
        /// <param name="webSocketMessage"></param>
        /// <param name="nowFiddlerRequsetChange"></param>
        /// <param name="ShowError"></param>
        /// <param name="ShowMes"></param>
        public static void ModificWebSocketMessage(Session oSession, WebSocketMessage webSocketMessage, IFiddlerHttpTamper nowFiddlerChange, bool isRequest, Action <string> ShowError, Action <string> ShowMes)
        {
            if (nowFiddlerChange.ParameterPickList != null)
            {
                PickSessionParameter(oSession, nowFiddlerChange, ShowError, ShowMes, webSocketMessage.IsOutbound, webSocketMessage);
            }
            ParameterContentModific payLoadModific = null;

            if (isRequest)
            {
                FiddlerRequestChange nowFiddlerRequsetChange = (FiddlerRequestChange)nowFiddlerChange;
                payLoadModific = nowFiddlerRequsetChange.BodyModific;
            }
            else
            {
                FiddlerResponseChange nowFiddlerResponseChange = (FiddlerResponseChange)nowFiddlerChange;
                payLoadModific = nowFiddlerResponseChange.BodyModific;
            }
            //Modific body
            if (payLoadModific != null && payLoadModific.ModificMode != ContentModificMode.NoChange)
            {
                if (payLoadModific.ModificMode == ContentModificMode.HexReplace)
                {
                    try
                    {
                        webSocketMessage.SetPayload(payLoadModific.GetFinalContent(webSocketMessage.PayloadAsBytes()));
                    }
                    catch (Exception ex)
                    {
                        ShowError(string.Format("error in GetFinalContent in HexReplace with [{0}]", ex.Message));
                    }
                }
                else
                {
                    if (webSocketMessage.FrameType == WebSocketFrameTypes.Binary)
                    {
                        ShowError("error in GetFinalContent that WebSocketFrameTypes is Binary ,just use <hex> mode");
                    }
                    else if (webSocketMessage.FrameType == WebSocketFrameTypes.Ping || webSocketMessage.FrameType == WebSocketFrameTypes.Pong || webSocketMessage.FrameType == WebSocketFrameTypes.Close)
                    {
                        // do nothing
                    }
                    else
                    {
                        string sourcePayload = webSocketMessage.PayloadAsString();
                        if (payLoadModific.ModificMode == ContentModificMode.ReCode)
                        {
                            try
                            {
                                webSocketMessage.SetPayload(payLoadModific.GetRecodeContent(sourcePayload));
                            }
                            catch (Exception ex)
                            {
                                ShowError(string.Format("error in GetRecodeContent in ReCode with [{0}]", ex.Message));
                            }
                        }
                        else
                        {
                            string errMes;
                            NameValueCollection nameValueCollection = new NameValueCollection();

                            //webSocketMessage.SetPayload(payLoadModific.GetFinalContent(sourcePayload));
                            string tempPayload = payLoadModific.GetFinalContent(sourcePayload, nameValueCollection, out errMes);
                            if (errMes != null)
                            {
                                ShowError(string.Format("error in GetFinalContent in PayLoadModific that [{0}]", errMes));
                            }
                            if (tempPayload != sourcePayload) //非标准协议的实现,或没有实现的压缩会导致PayloadAsString()使数据不可逆
                            {
                                webSocketMessage.SetPayload(tempPayload);
                            }

                            if (nameValueCollection != null && nameValueCollection.Count > 0)
                            {
                                ShowMes(string.Format("[ParameterizationContent]:{0}", nameValueCollection.MyToFormatString()));
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
 protected T ConvertEventArgs <T>(WebSocketMessage e) where T : EventArgs
 {
     return((T)e.Response);
 }
Ejemplo n.º 20
0
        private void OnMessage(object sender, WebSocketMessage webSocketMessage)
        {
            var e = (WebSocketClientWrapper.TextMessage)webSocketMessage.Data;

            _messageHandler(e.Message);
        }
Ejemplo n.º 21
0
        public bool Match(Session oSession, bool isRequest, WebSocketMessage webSocketMessage = null)
        {
            bool isWebSocket = webSocketMessage != null;// oSession.BitFlags.HasFlag(SessionFlags.IsWebSocketTunnel);
            bool isMatch     = true;

            if (isWebSocket)
            {
                if (!oSession.BitFlags.HasFlag(SessionFlags.IsWebSocketTunnel))
                {
                    return(false);
                }
                if (!((isRequest && webSocketMessage.IsOutbound) || (!isRequest && !webSocketMessage.IsOutbound)))
                {
                    return(false);
                }
                if (!UriMatch.Match(oSession.fullUrl))
                {
                    return(false);
                }
                if (BodyMatch != null)
                {
                    if (webSocketMessage.FrameType == WebSocketFrameTypes.Binary && BodyMatch.IsHexMatch)
                    {
                        if (!BodyMatch.Match(webSocketMessage.PayloadAsBytes()))
                        {
                            return(false);
                        }
                    }
                    else if (webSocketMessage.FrameType == WebSocketFrameTypes.Text && !BodyMatch.IsHexMatch)
                    {
                        if (!BodyMatch.Match(webSocketMessage.PayloadAsString()))
                        {
                            return(false);
                        }
                    }
                    else if (webSocketMessage.FrameType == WebSocketFrameTypes.Continuation)
                    {
                        //延续帧
                        return(false);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            else
            {
                if (UriMatch != null)
                {
                    if (!UriMatch.Match(oSession.fullUrl))
                    {
                        return(false);
                    }
                }
                if (HeadMatch != null)
                {
                    if (!HeadMatch.Match(true ? (HTTPHeaders)oSession.RequestHeaders : (HTTPHeaders)oSession.ResponseHeaders))
                    {
                        return(false);
                    }
                }
                if (BodyMatch != null)
                {
                    if (BodyMatch.IsHexMatch)
                    {
                        if (!BodyMatch.Match(true ? oSession.requestBodyBytes : oSession.responseBodyBytes))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        if (!BodyMatch.Match(true ? oSession.GetRequestBodyAsString() : oSession.GetResponseBodyAsString()))
                        {
                            return(false);
                        }
                    }
                }
            }
            return(isMatch);
        }
Ejemplo n.º 22
0
 public Task OnError(Exception exception, ModelA model, WebSocketMessage message, IHorseWebSocket client)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 23
0
        private Task SendMessage <T>(WebSocketMessage <T> message, CancellationToken cancellationToken)
        {
            var socket = GetActiveSocket();

            return(socket.SendAsync(message, cancellationToken));
        }
Ejemplo n.º 24
0
 internal static void DoOnWebSocketMessage(Session oS, WebSocketMessage oWSM)
 {
     EventHandler<WebSocketMessageEventArgs> onWebSocketMessage = OnWebSocketMessage;
     if (onWebSocketMessage != null)
     {
         onWebSocketMessage(oS, new WebSocketMessageEventArgs(oWSM));
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Handles <see cref="IWebSocket.Message"/> event.
 /// </summary>
 protected virtual void OnMessage(object sender, WebSocketMessage message)
 {
 }
Ejemplo n.º 26
0
        private void OnMessage(object sender, WebSocketMessage e)
        {
            var webSocket = (BitfinexWebSocketWrapper)sender;

            try
            {
                var token = JToken.Parse(e.Message);

                webSocket.ConnectionHandler.KeepAlive(DateTime.UtcNow);

                if (token is JArray)
                {
                    var channel = token[0].ToObject <int>();

                    if (token[1].Type == JTokenType.String)
                    {
                        var type = token[1].Value <string>();

                        switch (type)
                        {
                        // heartbeat
                        case "hb":
                            return;

                        // trade execution
                        case "te":
                            OnUpdate(webSocket, channel, token[2].ToObject <string[]>());
                            break;

                        // ignored -- trades already handled in "te" message
                        // https://github.com/bitfinexcom/bitfinex-api-node#te-vs-tu-messages
                        case "tu":
                            break;

                        default:
                            Log.Trace($"BitfinexSubscriptionManager.OnMessage(): Unexpected message type: {type}");
                            return;
                        }
                    }

                    // public channels
                    else if (channel != 0 && token[1].Type == JTokenType.Array)
                    {
                        if (token[1][0].Type == JTokenType.Array)
                        {
                            OnSnapshot(
                                webSocket,
                                channel,
                                token[1].ToObject <string[][]>()
                                );
                        }
                        else
                        {
                            // pass channel id as separate arg
                            OnUpdate(
                                webSocket,
                                channel,
                                token[1].ToObject <string[]>()
                                );
                        }
                    }
                }
                else if (token is JObject)
                {
                    var raw = token.ToObject <BaseMessage>();
                    switch (raw.Event.ToLowerInvariant())
                    {
                    case "subscribed":
                        OnSubscribe(webSocket, token.ToObject <ChannelSubscription>());
                        return;

                    case "unsubscribed":
                        OnUnsubscribe(webSocket, token.ToObject <ChannelUnsubscribing>());
                        return;

                    case "auth":
                    case "info":
                    case "ping":
                        return;

                    case "error":
                        var error = token.ToObject <ErrorMessage>();
                        // 10300 Subscription failed (generic) | 10301 : Already subscribed | 10302 : Unknown channel
                        // see https://docs.bitfinex.com/docs/ws-general
                        if (error.Code == 10300 || error.Code == 10301 || error.Code == 10302)
                        {
                            _subscribeErrorCode = error.Code;
                            _onSubscribeEvent.Set();
                        }
                        Log.Error($"BitfinexSubscriptionManager.OnMessage(): {e.Message}");
                        return;

                    default:
                        Log.Trace($"BitfinexSubscriptionManager.OnMessage(): Unexpected message format: {e.Message}");
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                _brokerage.OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
                throw;
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Sends string websocket message
 /// </summary>
 private static bool SendInternal(IConnector <TwinoWebSocket, WebSocketMessage> connector, string message)
 {
     byte[] data = _writer.Create(WebSocketMessage.FromString(message)).Result;
     return(connector.Send(data));
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Wss message handler
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public override void OnMessage(object sender, WebSocketMessage e)
 {
     OnMessageImpl(e);
 }
Ejemplo n.º 29
0
        private async Task MessageReceived(string socketMessage)
        {
            var model   = _serializer.ReadUtf8 <MessageReceivedModel>(new Utf8String(socketMessage));
            var message = new WebSocketMessage(model);

            switch (message.Type)
            {
            case MessageType.HEARTBEAT:
                await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Heartbeat received"));

                break;

            case MessageType.PUSH:
                await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Push received"));

                switch (message.ReceivedModel.Type)
                {
                case "mirror":
                    await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Mirror push"));

                    await _client.InternalPushReceivedAsync(new ReceivedPush(message.ReceivedModel));

                    break;

                case "dismissal":
                    await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Dismissed push"));

                    await _client.InternalPushDismissedAsync(new DismissedPush(message.ReceivedModel));

                    break;

                case "clip":
                    await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Copy received"));

                    await _client.InternalCopyReceivedAsync(new ReceivedCopy(message.ReceivedModel));

                    break;
                }
                break;

            case MessageType.TICKLE:
                await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Tickle received"));

                switch (message.SubType)
                {
                case SubType.DEVICE:
                    await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Device updated"));

                    await _client.UpdateDeviceCacheAsync();

                    break;

                case SubType.PUSH:
                    await _client.InternalLogAsync(new LogMessage(LogLevel.Debug, "Push updated"));

                    await _client.UpdatePushCacheAsync();

                    break;
                }

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(message.Type));
            }
        }
        /// <summary>
        /// Implementation of the OnMessage event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMessageImpl(object sender, WebSocketMessage e)
        {
            try
            {
                var token = JToken.Parse(e.Message);

                if (token is JArray)
                {
                    int channel = token[0].ToObject <int>();
                    //heartbeat
                    if (token[1].Type == JTokenType.String && token[1].Value <string>() == "hb")
                    {
                        return;
                    }
                    //public channels
                    if (channel != 0)
                    {
                        if (token.Count() == 2)
                        {
                            OnSnapshot(
                                token[0].ToObject <string>(),
                                token[1].ToObject <string[][]>()
                                );
                        }
                        else
                        {
                            // pass channel id as separate arg
                            OnUpdate(
                                token[0].ToObject <string>(),
                                token.ToObject <string[]>().Skip(1).ToArray()
                                );
                        }
                    }
                    else if (channel == 0)
                    {
                        string term = token[1].ToObject <string>();
                        switch (term.ToLower())
                        {
                        case "oc":
                            OnOrderClose(token[2].ToObject <string[]>());
                            return;

                        case "tu":
                            EmitFillOrder(token[2].ToObject <string[]>());
                            return;

                        default:
                            return;
                        }
                    }
                }
                else if (token is JObject)
                {
                    Messages.BaseMessage raw = token.ToObject <Messages.BaseMessage>();
                    switch (raw.Event.ToLower())
                    {
                    case "subscribed":
                        OnSubscribe(token.ToObject <Messages.ChannelSubscription>());
                        return;

                    case "unsubscribed":
                        OnUnsubscribe(token.ToObject <Messages.ChannelUnsubscribing>());
                        return;

                    case "auth":
                        var auth   = token.ToObject <Messages.AuthResponseMessage>();
                        var result = string.Equals(auth.Status, "OK", StringComparison.OrdinalIgnoreCase) ? "succeed" : "failed";
                        Log.Trace($"BitfinexWebsocketsBrokerage.OnMessage: Subscribing to authenticated channels {result}");
                        return;

                    case "info":
                    case "ping":
                        return;

                    case "error":
                        var error = token.ToObject <Messages.ErrorMessage>();
                        Log.Trace($"BitfinexWebsocketsBrokerage.OnMessage: {error.Level}: {error.Message}");
                        return;

                    default:
                        Log.Trace($"BitfinexWebsocketsBrokerage.OnMessage: Unexpected message format: {e.Message}");
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
                throw;
            }
        }
        private void WebSocket_OnClientApplicationMessageReceive(WebSocketSession session, WebSocketMessage message)
        {
            Invoke(new Action(() =>
            {
                if (!isStop)
                {
                    textBox8.AppendText($"OpCode:[{message.OpCode}] Mask:[{message.HasMask}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine);
                }
            }));

            // 应答客户端连接的情况下是需要进行返回数据的,此处演示返回的是原始的数据,追加一个随机数,你可以自己根据业务来决定返回什么数据
            if (session.IsQASession)
            {
                wsServer.SendClientPayload(session, Encoding.UTF8.GetString(message.Payload) + random.Next(1000, 10000));
            }

            // wsServer.AddSessionTopic( session, Encoding.UTF8.GetString( message.Payload ) );
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Wss message handler
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected override void OnMessage(object sender, WebSocketMessage e)
 {
     _messageHandler.HandleNewMessage(e);
 }
Ejemplo n.º 33
0
 private void OnMessage(object sender, WebSocketMessage e)
 {
     _messageHandler(e.Message);
 }
Ejemplo n.º 34
0
        private async Task OnMessage(string msg, CancellationToken ct)
        {
            if (!msg.IsValidJson(out var json))
            {
                return;
            }

            var message = new WebSocketMessage(json);

            switch (message.MessageType)
            {
            case "auth_required":
                LogInfo("Authorization requested. Sending access token...");
                await SendWs(new AuthCommand(_accessToken), ct);

                return;

            case "auth_ok":
                LogInfo("Authorization completed, subscribing to events...");
                await SubscribeToEvents(ct);

                return;

            case "result":
                // Isn't an event, log and exit.
                LogDebug($"Result message: {msg.ToPrettyJson()}");
                return;

            case "event":
                break;                         // continue processing

            default:
            {
                // Isn't an event! And event's are what we're working with.
                LogWarn($"Unsupported message (not an 'event'): {msg.ToPrettyJson()}");
                return;
            }
            }

            var entId       = message.EventEntityId;
            var matchedApps = _apps
                              .Where(a => a.MatchEntity(entId))
                              .ToArray();

            if (!matchedApps.Any())
            {
                // No matched apps, log and exit.
                if (EncounteredEntityIdsWithoutSubscription.Add(entId))
                {
                    LogTrace($"First time encounter of message with an EntityId that we're not listening on: {entId}");
                }

                return;
            }

            // Found matched apps! Log and determine which type
            LogInfo(msg.ToPrettyJson());
            Click        clickData        = null;
            StateChanged stateChangedData = null;

            var eventType = message.EventType;

            switch (eventType)
            {
            case "click":
            {
                clickData = new Click {
                    ClickType = (string)json["event"]["data"]["click_type"]
                };
                break;
            }

            case "state_changed":
            {
                //entity_boolean doesn't have a "last_triggered" attribute.
                //if (!entId.Contains("input_boolean."))
                //{
                //    if (!message.HasNewStateWithLastTriggered)
                //    {
                //        return; // Irrelevant event, we need new states that has "last time triggered" otherwise it might be an event provoked by reloading Hass. Unsure about this.
                //    }
                //}
                if (!message.IsTheMostRelevantStateChangeEvent)
                {
                    return;                                     // Is most probably a 'duped' event, throw it away ..
                }

                if (!message.HasNewState)
                {
                    return;                                     // Irrelevant event, we need new states only ..
                }

                stateChangedData = message.DeserializeStateChanged();
                break;
            }
            }

            var eventData = new EventData(entId, stateChangedData, clickData, msg);

            foreach (var hassApp in matchedApps)
            {
                hassApp.DispatchEvent(eventData);
            }
        }
Ejemplo n.º 35
0
 public virtual ValueTask SendAsync(WebSocketMessage message)
 {
     return(this.Channel.SendAsync(_messageEncoder, message));
 }
Ejemplo n.º 36
0
        public Task SendAsync <T>(WebSocketMessage <T> message, CancellationToken cancellationToken)
        {
            var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);

            return(_socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken));
        }
        public async ValueTask Handle(IAppSession session, WebSocketPackage package)
        {
            var websocketSession = session as WebSocketSession;

            if (package.OpCode == OpCode.Handshake)
            {
                websocketSession.HttpHeader = package.HttpHeader;

                // handshake failure
                if (!(await HandleHandshake(websocketSession, package)))
                {
                    websocketSession.CloseWithoutHandshake();
                    return;
                }

                websocketSession.Handshaked = true;
                await(session.Server as WebSocketService).OnSessionHandshakeCompleted(websocketSession);
                return;
            }


            if (!websocketSession.Handshaked)
            {
                // not pass handshake but receive data package now
                // impossible routine
                return;
            }

            if (package.OpCode == OpCode.Close)
            {
                if (websocketSession.CloseStatus == null)
                {
                    var closeStatus = GetCloseStatusFromPackage(package);

                    websocketSession.CloseStatus = closeStatus;

                    var message = new WebSocketMessage();

                    message.OpCode = OpCode.Close;
                    message.Data   = package.Data;

                    try
                    {
                        await websocketSession.SendAsync(message);
                    }
                    catch (InvalidOperationException)
                    {
                        // support the case the client close the connection right after it send the close handshake
                    }
                }
                else
                {
                    websocketSession.CloseWithoutHandshake();
                }

                return;
            }
            else if (package.OpCode == OpCode.Ping)
            {
                var message = new WebSocketMessage();

                message.OpCode = OpCode.Pong;
                message.Data   = package.Data;

                await websocketSession.SendAsync(message);

                return;
            }

            var protocolHandler = websocketSession.SubProtocolHandler;

            if (protocolHandler != null)
            {
                await protocolHandler.Handle(session, package);

                return;
            }

            // application command
            var websocketCommandMiddleware = _websocketCommandMiddleware;

            if (websocketCommandMiddleware != null)
            {
                await websocketCommandMiddleware.Handle(session, package);

                return;
            }

            var packageHandleDelegate = _packageHandlerDelegate;

            if (packageHandleDelegate != null)
            {
                await packageHandleDelegate(websocketSession, package);
            }
        }
Ejemplo n.º 38
0
        public static void PickSessionParameter(Session oSession, IFiddlerHttpTamper nowFiddlerHttpTamper, Action <string> ShowError, Action <string> ShowMes, bool isRequest, WebSocketMessage webSocketMessage = null)
        {
            Func <string, ParameterPick, string> PickFunc = (sourceStr, parameterPick) =>
            {
                try { return(ParameterPickTypeEngine.dictionaryParameterPickFunc[parameterPick.PickType].ParameterPickFunc(sourceStr, parameterPick.PickTypeExpression, parameterPick.PickTypeAdditional)); }
                catch (Exception) { return(null); }
            };

            bool isWebSocket = webSocketMessage != null;

            if (nowFiddlerHttpTamper.ParameterPickList != null)
            {
                foreach (ParameterPick parameterPick in nowFiddlerHttpTamper.ParameterPickList)
                {
                    string pickResult = null;
                    string pickSource = null;
                    switch (parameterPick.PickRange)
                    {
                    case ParameterPickRange.Line:
                        if (isRequest)
                        {
                            pickSource = oSession.fullUrl;
                            if (string.IsNullOrEmpty(pickSource))
                            {
                                pickResult = null;
                                break;
                            }
                        }
                        else
                        {
                            if (oSession.oResponse.headers == null)
                            {
                                pickResult = null;
                                break;
                            }
                            else
                            {
                                //pickSource = string.Format("{0} {1} {}", oSession.oResponse.headers.HTTPVersion, oSession.oResponse.headers.HTTPResponseCode,oSession.oResponse.headers.StatusDescription);
                                pickSource = string.Format("{0} {1}", oSession.oResponse.headers.HTTPVersion, oSession.oResponse.headers.HTTPResponseStatus);
                            }
                        }
                        pickResult = PickFunc(pickSource, parameterPick);
                        break;

                    case ParameterPickRange.Heads:
                        if (isWebSocket)
                        {
                            ShowError("[ParameterizationPick] can not pick parameter in head when the session is websocket");
                            break;
                        }
                        IEnumerable <HTTPHeaderItem> headerItems = isRequest ? (IEnumerable <HTTPHeaderItem>)oSession.RequestHeaders : (IEnumerable <HTTPHeaderItem>)oSession.ResponseHeaders;
                        foreach (HTTPHeaderItem tempHead in headerItems)
                        {
                            pickResult = PickFunc(tempHead.ToString(), parameterPick);
                            if (pickResult != null)
                            {
                                break;
                            }
                        }
                        break;

                    case ParameterPickRange.Entity:
                        if (isWebSocket)
                        {
                            if (webSocketMessage.PayloadLength == 0)
                            {
                                pickResult = null;
                                break;
                            }
                            pickSource = webSocketMessage.PayloadAsString();
                            pickResult = PickFunc(pickSource, parameterPick);
                        }
                        else
                        {
                            if (((oSession.requestBodyBytes == null || oSession.requestBodyBytes.Length == 0) && isRequest) && ((oSession.ResponseBody == null || oSession.ResponseBody.Length == 0) && isRequest))
                            {
                                pickResult = null;
                                break;
                            }
                            pickSource = isRequest ? oSession.GetRequestBodyAsString() : oSession.GetResponseBodyAsString();
                            pickResult = PickFunc(pickSource, parameterPick);
                        }
                        break;

                    default:
                        ShowError("[ParameterizationPick] unkonw pick range");
                        break;
                    }
                    if (pickResult == null)
                    {
                        ShowMes(string.Format("[ParameterizationPick] can not find the parameter with [{0}]", parameterPick.ParameterName));
                    }
                    else
                    {
                        ShowMes(string.Format("[ParameterizationPick] pick the parameter [{0} = {1}]", parameterPick.ParameterName, pickResult));
                        if (nowFiddlerHttpTamper.ActuatorStaticDataController.SetActuatorStaticData(parameterPick.ParameterName, pickResult))
                        {
                            ShowMes(string.Format("[ParameterizationPick] add the parameter [{0}] to ActuatorStaticDataCollection", parameterPick.ParameterName));
                        }
                        else
                        {
                            ShowError(string.Format("[ParameterizationPick] fail to add the parameter [{0}] to ActuatorStaticDataCollection", parameterPick.ParameterName));
                        }
                    }
                }
            }
            else
            {
                ShowError("[ParameterizationPick] not find ParameterPick to pick");
            }
        }
Ejemplo n.º 39
0
	public void SendMessage(WebSocketMessage msg)
	{
		//フラグメントヘッダを生成する
		var wsfi = new WebSocketFragmentInfo();
		wsfi.FIN = true;
		wsfi.Opcode = msg.IsTextData ?
		WebSocketFragmentOpcode.Text : 
		WebSocketFragmentOpcode.Binary;
		
		wsfi.MASK = false;
		
		byte[] data = msg.GetData();

		if(data.Length <= 125)
		{
			wsfi.PayloadLengthBits = PayloadLengthBits.Bits_7;
		}else if(data.Length <= 65535){
			wsfi.PayloadLengthBits = PayloadLengthBits.Bits_23;
		}else{
			wsfi.PayloadLengthBits = PayloadLengthBits.Bits_71;
		}

		wsfi.PayloadLength = (ulong)data.LongLength;
		byte[] fragment_header_data = wsfi.ToBinary();

		//データを送信。
		lock(send_lock_object)
		{
			stream.Write(fragment_header_data,0,fragment_header_data.Length);
			stream.Write(data,0,data.Length);
		}
	}