コード例 #1
0
ファイル: Serving.cs プロジェクト: goekboet/wsr
 public static IObservable <byte[]> Accept(
     Request r,
     IObservable <byte> bs,
     Func <Request, Func <WSFrame, IObservable <WSFrame> > > routes) =>
 Observable.Return(Encoding.ASCII.GetBytes(
                       string.Join("\r\n", new[]
 {
     "HTTP/1.1 101 Switching Protocols",
     "Upgrade: websocket",
     "Connection: Upgrade",
     $"Sec-WebSocket-Accept: {ResponseKey(r.Headers["Sec-WebSocket-Key"])}",
     "\r\n"
 })))
 .Concat(Websocket(routes(r))(bs));
コード例 #2
0
        public void Subscribe_And_Listen()
        {
            socket = new Websocket(new ApiCredentials
            {
                ApiKey    = TestBase.ApiKey,
                ApiSecret = TestBase.ApiSecret
            });

            socket.OnClientReady  += Socket_OnClientReady;
            socket.OnClosed       += Socket_OnClosed;
            socket.OnError        += Socket_OnError;
            socket.OnFatality     += Socket_OnFatality;
            socket.OnOrderMessage += Socket_OnOrderMessage;
            socket.OnSendFailed   += Socket_OnSendFailed;
            socket.OnStateChanged += Socket_OnStateChanged;
            socket.OnTradeMessage += Socket_OnTradeMessage;

            //socket.OnBlockMessage += Socket_OnBlockMessage;
            //socket.OnChannelsResponse += Socket_OnChannelsResponse;
            //socket.OnExchangesResponse += Socket_OnExchangesResponse;
            //socket.OnFavoriteMessage += Socket_OnFavoriteMessage;
            //socket.OnMessage += Socket_OnMessage;
            //socket.OnNewMarketMessage += Socket_OnNewMarketMessage;
            //socket.OnNewsMessage += Socket_OnNewsMessage;
            //socket.OnNotificationMessage += Socket_OnNotificationMessage;

            socket.Connect();

            resetEvent.WaitOne();
        }
コード例 #3
0
        public virtual IConnectionMethod SetConnectionMethod(string nodehost, ConnectionMethod method)
        {
            try
            {
                IConnectionMethod connectionMethod;

                switch (method)
                {
                case ConnectionMethod.RPC:
                    connectionMethod = new RPC(nodehost);
                    break;

                case ConnectionMethod.REST:
                    connectionMethod = new REST(nodehost);
                    break;

                case ConnectionMethod.Websocket:
                    connectionMethod = new Websocket(nodehost);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(method), method, null);
                }

                return(connectionMethod);
            }
            catch { throw; }
        }
コード例 #4
0
        /// <summary>
        /// Start a websocket for observing order events
        /// </summary>
        public void OrderEventStart(object sender, EventArgs e)
        {
            /* a hack to just reuse the REST API client to sign out websocket headers */
            var    re  = new Requests();
            string url = "wss://api.gemini.com/v1/order/events";

            try
            {
                GeminiClient.Wallet.Authenticate(re, new Gemini.Contracts.PrivateRequest()
                {
                    Request = "/v1/order/events"
                });
                if (GeminiClient.Wallet.Url().Contains("sandbox"))
                {
                    url = "wss://api.sandbox.gemini.com/v1/order/events";
                }
                Gemini.Websocket ws = new Websocket(url, OrderEventCallback, null);

                ws.AddHeader("X-GEMINI-APIKEY", re.Headers["X-GEMINI-APIKEY"]);
                ws.AddHeader("X-GEMINI-PAYLOAD", re.Headers["X-GEMINI-PAYLOAD"]);
                ws.AddHeader("X-GEMINI-SIGNATURE", re.Headers["X-GEMINI-SIGNATURE"]);
                ws.Connect();
                sockets.Add(ws);
            }
            catch (Exception ex)
            {
                Logger.WriteException(Logger.Level.Error, ex);
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error opening websocket");
            }
        }
コード例 #5
0
ファイル: MixerChat.cs プロジェクト: mixer/chat-unity
    private IEnumerator InitializeCoRoutine()
    {
        _channelURL = _baseURL + _channelID;
        using (UnityWebRequest request = UnityWebRequest.Get(_channelURL))
        {
            yield return(request.SendWebRequest());

            if (request.isNetworkError)
            {
                Debug.Log("Error: Could not retrieve websocket URL to connect to chat. " + request.error);
            }
            else // Success
            {
                string websocketHostsJson = request.downloadHandler.text;
                ParseWebsocketConnectionInformation(websocketHostsJson);
                // Find a websocket to connect to.
                Dictionary <string, string> headers = new Dictionary <string, string>();
                _websocket            = GetComponent <Websocket>();
                _websocket.OnOpen    += _websocket_OnOpen;
                _websocket.OnMessage += _websocket_OnMessage;
                _websocket.OnError   += _websocket_OnError;
                _websocket.OnClose   += _websocket_OnClose;
                _websocket.Open(new Uri(_websocketURL));
            }
        }
    }
コード例 #6
0
            public UniRx.IObservable <Websocket> Connection(Config config)
            {
                return(UniRx.Observable.Create <Websocket> (observer => {
                    var impl = new WebSocketSharp.WebSocket(config.url.ToString(), config.protocols);
                    System.EventHandler <WebSocketSharp.ErrorEventArgs> onError = (obj, e) => {
                        observer.OnError(new System.Exception(e.Message));
                    };

                    impl.OnError += onError;

                    foreach (var pr in config.coockie)
                    {
                        impl.SetCookie(new WebSocketSharp.Net.Cookie(pr.Key, pr.Value));
                    }

                    var socket = new Websocket(impl, shared_data);
                    impl.OnOpen += (sender, e) => {
                        impl.OnError -= onError;
                        this.shared_data.connected.Add(socket.GetHashCode(), socket);

                        observer.OnNext(socket);
                        observer.OnCompleted();
                    };
                    impl.ConnectAsync();

                    return new Sas.DisposeAction(() => {
                    });
                }));
            }
コード例 #7
0
        public async Task SendMessageAsync(string method, object requestParams, Action <JToken> callBack)
        {
            var requestId = StringExtensions.RandomString;

            if (callBack != null)
            {
                Callbacks.Add(requestId, callBack);
            }
            await Websocket.SendAsync(PackMessage(method, requestId, requestParams), WebSocketMessageType.Text, true,
                                      CancellationToken.None);
        }
コード例 #8
0
 private void Awake()
 {
     if (Instance != null)
     {
         Destroy(this);
     }
     else
     {
         Instance = this;
         DontDestroyOnLoad(gameObject);
     }
 }
コード例 #9
0
        static void Main(string[] args)
        {
            Console.Title = "jschat1";
            websocket     = new Websocket(IPAddress.Any, 8001);
            clientlist    = new List <ClientInstance>();

            while (true)
            {
                accept();
                receive();
                Thread.Sleep(50);
            }
        }
コード例 #10
0
        public async Task ReceiveAsync(IChatOptions chatOptions)
        {
            _chatOptions = chatOptions;
            var ws = _ws;

            if (ws != null)
            {
                throw new InvalidOperationException("_ws is not null");
            }
            var heartbeatTimer = new System.Timers.Timer
            {
                Interval  = 1000,
                AutoReset = true,
            };

            heartbeatTimer.Elapsed += HeartbeatTimer_Elapsed;
            ws = new Websocket
            {
                //AutoSendPingInterval = 1000,
                //EnableAutoSendPing = true,
                NoDelay     = true,
                SubProtocol = "msg.nicovideo.jp#json",
                Origin      = "https://live2.nicovideo.jp",
                UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
            };
            _ws          = ws;
            ws.Received += Ws_Received;
            ws.Opened   += (s, e) =>
            {
                OnWebsocketOpened();
                heartbeatTimer.Enabled = true;
            };
            var url = "wss://msgd.live2.nicovideo.jp/websocket";

            try
            {
                Debug.WriteLine("ChatProvider::ReceiveAsync() ws.ReceiveAsync() start");
                await ws.ReceiveAsync(url);

                Debug.WriteLine("ChatProvider::ReceiveAsync() ws.ReceiveAsync() finished");
            }
            finally
            {
                heartbeatTimer.Elapsed -= HeartbeatTimer_Elapsed;
                heartbeatTimer.Enabled  = false;
                ws.Received            -= Ws_Received;
                ws.Opened -= Ws_Opened;
                _ws        = null;
            }
        }
コード例 #11
0
        public MarketHub()
        {
            socket = new Websocket(new API.Models.ApiCredentials
            {
                ApiKey    = "[YOUR-API-KEY]",
                ApiSecret = "[YOUR-API-SECRET]"
            });

            socket.OnClientReady  += Socket_OnClientReady;
            socket.OnTradeMessage += Socket_OnTradeMessage;
            socket.OnError        += Socket_OnError;

            socket.Connect();
        }
コード例 #12
0
        static void Main(string[] args)
        {
            Console.Title = "jsserver3";
            websocket = new Websocket(IPAddress.Any, 8001);

            while (true) {
                Socket client = websocket.AcceptSocket();
                if (client != null)
                    clientlist.Add(new ClientInstance(client));

                receiveData();

                sendData();
            }
        }
コード例 #13
0
    private void Start()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }

        Debug.Log("START FRONTEND");
        instance = this;
        socket   = GetComponent <Websocket>();
        socket.onCloseCallback  = () => SetState(unconnectedState);
        socket.onErrorCallback += (err) => SetState(unconnectedState);
        CreateStates();
        SetState(unconnectedState);
        StartCoroutine(UpdateNetworkObjsCoroutine());
    }
コード例 #14
0
        static void Main(string[] args)
        {
            Console.Title = "jsserver3";
            websocket     = new Websocket(IPAddress.Any, 8001);

            while (true)
            {
                Socket client = websocket.AcceptSocket();
                if (client != null)
                {
                    clientlist.Add(new ClientInstance(client));
                }

                receiveData();

                sendData();
            }
        }
コード例 #15
0
 public async Task ReceiveAsync(string websocketUrl)
 {
     if (_ws != null)
     {
         return;
     }
     _ws           = new Websocket();
     _ws.Received += Ws_Received;
     _ws.Opened   += Ws_Opened;
     try
     {
         await _ws.ReceiveAsync(websocketUrl);
     }
     finally
     {
         _ws.Received -= Ws_Received;
         _ws           = null;
     }
 }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>

        public 实体ViewModel()
        {
            UserInfo = new 实体类();

            //下拉框的初始数据
            CombboxList = new List <ComplexInfoModel>()
            {
                new ComplexInfoModel()
                {
                    Key = "1", Text = "苹果"
                },
                new ComplexInfoModel()
                {
                    Key = "2", Text = "香蕉"
                }
            };


            Thread t = new Thread(delegate()
            {
                // replace the IP with your system IP Address...
                Server myserver = new Server("127.0.0.1", 13000, UserInfo);
            });

            t.Start();

            Console.WriteLine("Server Started...!");
            Client tcp通讯 = new Client(UserInfo);

            LoadTcpClient = new RelayCommand(CQCQCQ);


            Thread t2 = new Thread(async delegate()
            {
                // replace the IP with your system IP Address...
                Websocket myserver = new Websocket();
                await myserver.Server();
            });

            t2.Start();
        }
コード例 #17
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     Acsrf             = new Acsrf(this);
     AjaxSpider        = new AjaxSpider(this);
     Alert             = new Generated.Alert(this);
     AlertFilter       = new AlertFilter(this);
     Ascan             = new Ascan(this);
     Authentication    = new Authentication(this);
     Authorization     = new Authorization(this);
     AutoUpdate        = new AutoUpdate(this);
     Brk               = new Break(this);
     Context           = new Context(this);
     Core              = new Core(this);
     ForcedUser        = new ForcedUser(this);
     HttpSessions      = new HttpSessions(this);
     ImportLogFiles    = new ImportLogFiles(this);
     ImportUrls        = new ImportUrls(this);
     LocalProxies      = new LocalProxies(this);
     OpenApi           = new OpenApi(this);
     Parameters        = new Params(this);
     Pnh               = new Pnh(this);
     PScan             = new PScan(this);
     Replacer          = new Replacer(this);
     Reveal            = new Reveal(this);
     RuleConfig        = new RuleConfig(this);
     Script            = new Script(this);
     Search            = new Search(this);
     Selenium          = new Selenium(this);
     SessionManagement = new SessionManagement(this);
     Soap              = new Soap(this);
     Spider            = new Spider(this);
     Stats             = new Stats(this);
     Users             = new Users(this);
     Websocket         = new Websocket(this);
 }
コード例 #18
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     acsrf             = new Acsrf(this);
     ajaxspider        = new AjaxSpider(this);
     alert             = new OWASPZAPDotNetAPI.Generated.Alert(this);
     alertFilter       = new AlertFilter(this);
     ascan             = new Ascan(this);
     authentication    = new Authentication(this);
     authorization     = new OWASPZAPDotNetAPI.Generated.Authorization(this);
     autoupdate        = new Autoupdate(this);
     brk               = new Break(this);
     context           = new Context(this);
     core              = new Core(this);
     forcedUser        = new ForcedUser(this);
     httpSessions      = new HttpSessions(this);
     importLogFiles    = new ImportLogFiles(this);
     importurls        = new Importurls(this);
     localProxies      = new LocalProxies(this);
     openapi           = new Openapi(this);
     parameters        = new Params(this);
     pnh               = new Pnh(this);
     pscan             = new Pscan(this);
     replacer          = new Replacer(this);
     reveal            = new Reveal(this);
     ruleConfig        = new RuleConfig(this);
     script            = new Script(this);
     search            = new Search(this);
     selenium          = new Selenium(this);
     sessionManagement = new SessionManagement(this);
     soap              = new Soap(this);
     spider            = new Spider(this);
     stats             = new Stats(this);
     users             = new Users(this);
     websocket         = new Websocket(this);
 }
コード例 #19
0
ファイル: Program.cs プロジェクト: slofurno/minesweepers
    static async Task ProcessWebSocket(Websocket ws, ConnectionHub connectionHub, BufferBlock<GameTask> gameTasks)
    {
      var uc = new UserConnection(ws);
      await connectionHub.Add(uc);

      var hash = Guid.NewGuid().ToString();
      var player = new PlayerState() { Name = "player", Color = "blue", Hash = hash };


      var first = new PlayerInit() { Hash = hash, Height = 0, Width = 0 };
      var json = JSON.Serialize(first);

      var initPacket = new UpdatePacket() { Type = "init", Data = json };
      var ip = JSON.Serialize(initPacket);
      await uc.SendAsync(ip);

      ReadWebsocket(ws, gameTasks, uc, player);

      var initTask = new InitTask(uc, player);
      await gameTasks.SendAsync(initTask);

      await uc.Worker();
      Console.WriteLine("disconnected");
      
      //FIXME: this is never pushed to currently connected clients
      player.Dead = true;
      await connectionHub.Remove(uc);
    }
コード例 #20
0
        void WebsocketClient()
        {
            Websocket myserver = new Websocket();

            myserver.Client();
        }
コード例 #21
0
        private void BeginProcessMessage()
        {
            new Thread(async() =>
            {
                while (Running)
                {
                    try
                    {
                        var buffer = new byte[1024 * 1024]; //1mb
                        var result = await Websocket.ReceiveAsync(buffer, CancellationToken.None);
                        var bytes  = new byte[result.Count];
                        Array.Copy(buffer, bytes, result.Count);
                        var json     = JToken.Parse(Encoding.UTF8.GetString(bytes));
                        var typeCode = json["TypeCode"].ToString();
                        if (typeCode.EqualsIgnoreCase("Event"))
                        {
                            var type = (MahuaMessageType)json["EventType"].ToObject <int>();
                            if (type == MahuaMessageType.Friend || type == MahuaMessageType.Group)
                            {
                                var message = new AcceptedMessage()
                                {
                                    FromGroup      = json["FromNum"].ToObject <long>(),
                                    FromUser       = json["EventOperator"].ToObject <long>(),
                                    Content        = json["Message"].ToString(),
                                    IsGroupMessage = type == MahuaMessageType.Group
                                };
                                ReceivedMessageEvent?.Invoke(this, message);
                            }
                            continue;
                        }

                        if (typeCode.EqualsIgnoreCase("Api_GetQQListApiOut"))
                        {
                            QQ = json["Result"].ToObject <long>();
                            continue;
                        }
                        //WDNM为什么HTTP API请求过去的返回值会跑到Websocket返回
                        if (Callbacks.ContainsKey(typeCode.ToLower()))
                        {
                            Callbacks[typeCode.ToLower()]?.Invoke(json);
                            Callbacks.Remove(typeCode.ToLower());
                            continue;
                        }
                    }
                    catch
                    {
                        if (Running && Websocket.State != WebSocketState.Open)
                        {
                            try
                            {
                                Websocket = new ClientWebSocket();
                                await Websocket.ConnectAsync(new Uri(WebsocketUrl), CancellationToken.None);
                            }
                            catch
                            {
                                LogHelper.Error("Cannot reconnect websocket.");
                            }
                        }
                    }
                }
            }).Start();
        }
コード例 #22
0
ファイル: WebsocketClient.cs プロジェクト: MrLurk/WebSocket
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public Task SendMessageAsync(string message)
        {
            var msg = Encoding.UTF8.GetBytes(message);

            return(Websocket.SendAsync(new ArraySegment <byte>(msg, 0, msg.Length), WebSocketMessageType.Text, true, CancellationToken.None));
        }
コード例 #23
0
        private void BeginProcessMessage()
        {
            new Thread(async() =>
            {
                while (Running)
                {
                    try
                    {
                        var buffer = new byte[1024 * 1024]; //1mb
                        var result = await Websocket.ReceiveAsync(buffer, CancellationToken.None);
                        var json   = JToken.Parse(Encoding.UTF8.GetString(buffer.Take(result.Count).ToArray()));
                        if (json["id"] != null && Callbacks.ContainsKey(json["id"].ToString()))
                        {
                            Callbacks[json["id"].ToString()].Invoke(json);
                            Callbacks.Remove(json["id"].ToString());
                            continue;
                        }

                        if (json["event"] != null)
                        {
                            switch (json["event"].ToString())
                            {
                            case "message":
                                var type = json["params"]["type"].ToObject <LightMessageType>();
                                if (type == LightMessageType.Group || type == LightMessageType.Friend)
                                {
                                    var message = new AcceptedMessage()
                                    {
                                        IsGroupMessage = type == LightMessageType.Group,
                                        Content        = json["params"]["content"].ToString(),
                                        FromGroup      = type == LightMessageType.Group
                                                ? json["params"]["group"].ToObject <long>()
                                                : 0,
                                        FromUser = json["params"]["qq"].ToObject <long>()
                                    };
                                    ReceivedMessageEvent?.Invoke(this, message);
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        if (Running && Websocket.State != WebSocketState.Open)
                        {
                            try
                            {
                                Websocket = new ClientWebSocket();
                                await Websocket.ConnectAsync(new Uri(ListenUrl), CancellationToken.None);
                            }
                            catch
                            {
                                LogHelper.Error("Cannot reconnect websocket.");
                            }
                        }
                    }
                }
            }).Start();
            Task.Factory.StartNew(async() =>
            {
                while (Running)
                {
                    await Task.Delay(500);
                    if (SendingMessageQueue.Any())
                    {
                        var message = SendingMessageQueue.Dequeue();
                        if (message.Contents.All(v => v.Type != MessageType.Image))
                        {
                            await SendMessageAsync("sendMessage", new
                            {
                                type    = LightMessageType.Group,
                                group   = message.TargetGroupId.ToString(),
                                content = message.ToString()
                            });
                        }
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
コード例 #24
0
 public UserConnection(Websocket websocket)
 {
   _ws = websocket;
   _queue = new BufferBlock<String>();
 }
コード例 #25
0
 public override void Send(string data) => Websocket.Send(data);
コード例 #26
0
    private void Initialize()
    {
        if (mixerDialog == null)
        {
            mixerDialog = FindObjectOfType <MixerInteractiveDialog>();
        }
        if (queuedEvents == null)
        {
            queuedEvents = new List <InteractiveEventArgs>();
        }
        // Listen for interactive events
        bool interactivityManagerAlreadyInitialized = false;

        if (interactivityManager == null)
        {
            interactivityManager = InteractivityManager.SingletonInstance;

            interactivityManager.OnError -= HandleError;
            interactivityManager.OnInteractivityStateChanged       -= HandleInteractivityStateChanged;
            interactivityManager.OnParticipantStateChanged         -= HandleParticipantStateChanged;
            interactivityManager.OnInteractiveButtonEvent          -= HandleInteractiveButtonEvent;
            interactivityManager.OnInteractiveJoystickControlEvent -= HandleInteractiveJoystickControlEvent;
            interactivityManager.OnInteractiveMessageEvent         -= HandleInteractiveMessageEvent;

            interactivityManager.OnError += HandleError;
            interactivityManager.OnInteractivityStateChanged       += HandleInteractivityStateChanged;
            interactivityManager.OnParticipantStateChanged         += HandleParticipantStateChanged;
            interactivityManager.OnInteractiveButtonEvent          += HandleInteractiveButtonEvent;
            interactivityManager.OnInteractiveJoystickControlEvent += HandleInteractiveJoystickControlEvent;
            interactivityManager.OnInteractiveMessageEvent         += HandleInteractiveMessageEvent;
        }
        else
        {
            interactivityManagerAlreadyInitialized = true;
        }
        MixerInteractiveHelper helper = MixerInteractiveHelper.SingletonInstance;

        helper.runInBackgroundIfInteractive = runInBackground;
        helper.defaultSceneID = defaultSceneID;
        for (int i = 0; i < groupIDs.Count; i++)
        {
            string groupID = groupIDs[i];
            if (groupID != string.Empty &&
                !helper.groupSceneMapping.ContainsKey(groupID))
            {
                helper.groupSceneMapping.Add(groupID, sceneIDs[i]);
            }
        }

        if (outstandingCreateGroupsRequests == null)
        {
            outstandingCreateGroupsRequests = new List <string>();
        }
        outstandingSetDefaultSceneRequest   = string.Empty;
        processedSerializedProperties       = false;
        outstandingRequestsCompleted        = false;
        shouldCheckForOutstandingRequests   = false;
        lastCheckForOutstandingRequestsTime = -1;
#if !UNITY_WSA
        backgroundWorker = new BackgroundWorker();
#endif
        if (interactivityManagerAlreadyInitialized &&
            InteractivityManager.SingletonInstance.InteractivityState == InteractivityState.InteractivityEnabled)
        {
            ProcessSerializedProperties();
        }
        websocket = gameObject.AddComponent <Websocket>();
        InteractivityManager.SingletonInstance.SetWebsocketInstance(websocket);
    }
コード例 #27
0
ファイル: Program.cs プロジェクト: slofurno/minesweepers
    static async Task ReadWebsocket(Websocket ws, BufferBlock<GameTask> gameTasks, UserConnection uc, PlayerState player)
    {
      string next;
      while ((next = await ws.ReadFrame()) != null)
      {
        var update = JSON.Deserialize<PlayerCommand>(next);

        if (player.Dead)
        {
          //this is now checked in two places, but at least dead players won't send move commands to the main work channel
          continue;
        }

        dynamic command = ParseCommand(update);

        if (command == null)
        {
          continue;
        }

        var updatetask = new UpdateTask(command, player);
        await gameTasks.SendAsync(updatetask);
      }

      uc.Closed = true;
      await uc.SendAsync(null);
    }
コード例 #28
0
        public async Task CommentReceiveTest()
        {
            var guid            = Guid.NewGuid();
            var optionsMock     = new Mock <ICommentOptions>();
            var siteOptionsMock = new Mock <OpenrecSiteOptions>();
            var loggerMock      = new Mock <ILogger>();
            var userMock        = new Mock <IUser2>();

            userMock.Setup(u => u.UserId).Returns("123");
            var userStoreMock = new Mock <IUserStoreManager>();

            userStoreMock.Setup(u => u.GetUser(SiteType.Openrec, It.IsAny <string>())).Returns(userMock.Object);
            var browserProfileMock = new Mock <IBrowserProfile>();
            var ws = new Websocket();

            var bpMock = new Mock <IBlackListProvider>();

            var options        = optionsMock.Object;
            var siteOptions    = siteOptionsMock.Object;
            var logger         = loggerMock.Object;
            var userStore      = userStoreMock.Object;
            var browserProfile = browserProfileMock.Object;
            var movieInfo1     = new MovieInfo
            {
                MovieId = 1,
            };

            var cpMock = new Mock <CommentProvider>(options, siteOptions, logger, userStore);

            cpMock.Protected().Setup <List <Cookie> >("GetCookies", ItExpr.IsAny <IBrowserProfile>()).Returns(new List <Cookie>
            {
                new Cookie("uuid", "abc", "/", "a"),
                new Cookie("access_token", "abc", "/", "a"),
            });
            cpMock.Protected().Setup <Task <MovieInfo> >("GetMovieInfo", ItExpr.IsAny <string>()).Returns(Task.FromResult(movieInfo1));
            cpMock.Protected().Setup <IOpenrecWebsocket>("CreateOpenrecWebsocket").Returns(ws);
            cpMock.Protected().Setup <IBlackListProvider>("CreateBlacklistProvider").Returns(bpMock.Object);

            var cp = cpMock.Object;

            cp.SiteContextGuid = guid;
            var received = false;

            cp.MessageReceived += (s, e) =>
            {
                if (e.Message is IOpenrecComment comment)
                {
                    var metadata = e.Metadata;

                    Assert.AreEqual(new List <IMessagePart> {
                        Common.MessagePartFactory.CreateMessageText("そっくりだな")
                    }, comment.CommentItems);
                    Assert.AreEqual("258587691", comment.Id);
                    Assert.AreEqual(new List <IMessagePart> {
                        Common.MessagePartFactory.CreateMessageText("il")
                    }, comment.NameItems);
                    Assert.AreEqual(OpenrecMessageType.Comment, comment.OpenrecMessageType);
                    Assert.AreEqual("16:13:06", comment.PostTime);
                    //Assert.IsTrue(!string.IsNullOrEmpty(comment.Raw));
                    Assert.AreEqual(SiteType.Openrec, comment.SiteType);
                    Assert.IsNull(comment.UserIcon);
                    Assert.AreEqual("330854891", comment.UserId);

                    Assert.AreEqual(guid, metadata.SiteContextGuid);

                    ws.Disconnect();
                    received = true;
                }
            };
            var t = cp.ConnectAsync("", browserProfile);
            //コメントとExpectedをセットするだけでテストが書けるようにしたい
            var data1 = "42[\"message\",\"{\\\"type\\\":0,\\\"data\\\":{\\\"movie_id\\\":1257976,\\\"live_type\\\":1,\\\"onair_status\\\":1,\\\"user_id\\\":330854891,\\\"openrec_user_id\\\":1695348,\\\"user_name\\\":\\\"il\\\",\\\"user_type\\\":\\\"2\\\",\\\"user_key\\\":\\\"tropicalgorilla\\\",\\\"user_rank\\\":0,\\\"chat_id\\\":258587691,\\\"item\\\":0,\\\"golds\\\":0,\\\"message\\\":\\\"そっくりだな\\\",\\\"cre_dt\\\":\\\"2019-04-21 16:13:06\\\",\\\"is_fresh\\\":0,\\\"is_warned\\\":0,\\\"is_moderator\\\":0,\\\"is_premium\\\":0,\\\"has_banned_word\\\":0,\\\"stamp\\\":null,\\\"quality_type\\\":0,\\\"user_icon\\\":\\\"https://openrec-appdata.s3.amazonaws.com/user/3308549/330854891.png?1555827558\\\",\\\"supporter_rank\\\":0,\\\"is_creaters\\\":0,\\\"is_premium_hidden\\\":0,\\\"user_color\\\":\\\"#F6A434\\\",\\\"yell\\\":null,\\\"yell_type\\\":null,\\\"to_user\\\":null,\\\"capture\\\":null,\\\"display_dt\\\":\\\"0秒前\\\",\\\"del_flg\\\":0}}\"]";

            ws.OnReceived(data1);
            await t;

            Assert.IsTrue(received);
        }