Beispiel #1
139
        public void Receive()
        {
            WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat"));

              ManualResetEvent receiveEvent = new ManualResetEvent(false);
              ws.OnMessage += (s, e) =>
              {
            receiveEvent.Set();
              };

              ws.Connect();
              ws.Send("login: User1");

              bool received = receiveEvent.WaitOne(TimeSpan.FromSeconds(2));
              Assert.IsTrue(received);

              receiveEvent.Close();
              ws.Close();
        }
        public void UsageTest()
        {
            var resetEvent = new ManualResetEvent(false);

            var location = new Uri("ws://echo.websocket.org");

            var client = new WebSocketClient(location);
            client.OnOpen = () => Debug.WriteLine("Connection Open");
            client.OnClose = () =>
            {
                Debug.WriteLine("Connection Closed");
                resetEvent.Set();
            };
            client.OnError = _ => Debug.WriteLine("error " + _);
            client.OnMessage = m =>
            {
                Debug.WriteLine(m);
                client.CloseAsync();
            };

            client.Connect();

            client.Send("Hello!");

            resetEvent.WaitOne();
        }
 public WebsocketService()
 {
     connection = new WebSocketClient();
     connection.Closed += OnWebsocketClosed;
     connection.Error += OnWebsocketError;
     connection.MessageReceived += OnWebsocketReceived;
     connection.AutoSendPongResponse = false;
     
 }
		async void Init(){		

			Client = new WebSocketClient ();
			Client.MessageReceived += OnMessage;

			await Client.OpenAsync("ws://echo.websocket.org");

			OnMessage("Client connected.");

		}
        private async Task TestWebsocketPortable()
        {
            var client = new WebSocketClient();
            client.Opened += websocket_Opened;
            client.Closed += websocket_Closed;
            client.MessageReceived += websocket_MessageReceived;
            client.Error += Client_Error;
            
            await client.OpenAsync("ws://echo.websocket.org");
            

            await client.SendAsync("Hello World");

            await client.SendAsync("Hello World2");

            await Task.Delay(1000);

            await client.CloseAsync();

            await Task.Delay(100);

            Debug.WriteLine("TestWebsocketPortable");
        }
 public async Task Connect_Success()
 {
     using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
     {
         Assert.True(context.WebSockets.IsWebSocketRequest);
         var webSocket = await context.WebSockets.AcceptWebSocketAsync();
     }))
     {
         var client = new WebSocketClient();
         using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
         {
         }
     }
 }
Beispiel #7
0
        private async Task TestWebsocketPortable()
        {
            var client = new WebSocketClient();
            client.Opened += websocket_Opened;
            client.Closed += websocket_Closed;
            client.MessageReceived += websocket_MessageReceived;

            //Never Ending
            await client.OpenAsync("ws://echo.websocket.org");

            await client.SendAsync("Hello World");

            await client.SendAsync("Hello World2");

            Debug.WriteLine("TestWebsocketPortable");
        }
Beispiel #8
0
        private static void ResetClient()
        {
            if (Client != null)
            {
                Client.Disconnect();
            }

            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };

            WebSocketClient customClient = new WebSocketClient(clientOptions);

            Client = new TwitchClient(customClient);
        }
 protected bool createSocket()
 {
     if (string.IsNullOrEmpty (host.Text)) {
         logText ("No host name");
         return false;
     }
     try {
         ws = new WebSocketClient (host.Text) {
             OnReceive = OnReceive,
             OnDisconnect = OnDisconnect
         };
         return true;
     } catch (System.Exception e) {
         logText ("Not a valid host name: " + e.Message);
         return false;
     }
 }
Beispiel #10
0
        static void Main(string[] args)
        {
            var firstArg = args.FirstOrDefault();

            if (string.IsNullOrWhiteSpace(firstArg))
            {
                Console.WriteLine("Select a client:");
                Console.WriteLine("");
                Console.WriteLine("gg  = destiny.gg");
                Console.WriteLine("ggl = destiny.gg listening only");
                Console.WriteLine("t   = twitch.tv");
                Console.WriteLine("tl  = twitch.tv listening only");
                Console.WriteLine("s   = sample client");
                firstArg = Console.ReadLine();
            }

            IClientVisitor client;

            switch (firstArg)
            {
            case "gg":
                client = new WebSocketClient(PrivateConstants.BotWebsocketAuth);
                break;

            case "ggl":
                client = new WebSocketListenerClient(PrivateConstants.BotWebsocketAuth);
                break;

            case "t":
                client = new SimpleIrcClient(server, port, channel, nick, pass);
                break;

            case "tl":
                client = new SimpleIrcListenerClient(server, port, channel, nick, pass);
                break;

            case "s":
                client = new SampleClient();
                break;

            default:
                throw new Exception("Invalid input");
            }

            new PrimaryLogic(client).Run();
        }
        public async Task Send_Start_ReceiveDataOnMutation_Large_Message()
        {
            using (TestServer testServer = CreateStarWarsServer())
            {
                // arrange
                WebSocketClient client    = CreateWebSocketClient(testServer);
                WebSocket       webSocket = await ConnectToServerAsync(client);

                var document = Utf8GraphQLParser.Parse(
                    "subscription { onReview(episode: NEWHOPE) { stars } }");

                var request = new GraphQLRequest(document);

                const string subscriptionId = "abc";

                // act
                await webSocket.SendSubscriptionStartAsync(
                    subscriptionId, request, true);

                // assert
                await webSocket.SendEmptyMessageAsync();

                await testServer.SendRequestAsync(new ClientQueryRequest
                {
                    Query = @"
                    mutation {
                        createReview(episode:NEWHOPE review: {
                            commentary: ""foo""
                            stars: 5
                        }) {
                            stars
                        }
                    }
                "
                });

                IReadOnlyDictionary <string, object> message =
                    await WaitForMessage(
                        webSocket,
                        MessageTypes.Subscription.Data,
                        TimeSpan.FromSeconds(15));

                Assert.NotNull(message);
                message.MatchSnapshot();
            }
        }
        private void ConfigureLogic()
        {
            var messages        = new List <string>();
            var listViewAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleExpandableListItem1, messages);

            listView.Adapter = listViewAdapter;

            Action <string> sendMessageCallback = (message) =>
            {
                RunOnUiThread(() => {
                    listViewAdapter.Add(message);
                    listViewAdapter.NotifyDataSetChanged();
                });
            };

            WebSocketClient.AddCallBack(ServerMethod.SendMessage, sendMessageCallback);
        }
        internal static async Task <Operation> ModifyOperation(WebSocketClient client, Operation modifiedOperation)
        {
            Operation dbOperation;
            bool      newOp = false;

            using (var ctx = new ScavengePadDbContext())
            {
                dbOperation = await ctx.Operations
                              .Where(c => c.Id == modifiedOperation.Id)
                              .Where(c => c.TeamId == client.User.TeamId)
                              .AsNoTracking()
                              .FirstOrDefaultAsync();

                if (dbOperation == null)
                {
                    dbOperation = new Operation()
                    {
                        TeamId     = client.User.TeamId,
                        Title      = modifiedOperation.Title,
                        Objectives = modifiedOperation.Objectives
                    };
                    ctx.Operations.Add(dbOperation);
                    newOp = true;
                }
                else
                {
                    ctx.Operations.Update(modifiedOperation);
                    dbOperation = modifiedOperation;
                }
                await ctx.SaveChangesAsync();

                if (newOp)
                {
                    dbOperation.OperationPadSuffix = WebUtility.UrlEncode(ScavengePadUtils.SHA256($"{dbOperation.Id}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}"));
                }
                foreach (var objective in dbOperation.Objectives)
                {
                    if (objective.ObjectivePadSuffix == "default")
                    {
                        objective.ObjectivePadSuffix = WebUtility.UrlEncode(ScavengePadUtils.SHA256($"{objective.Id}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}{ScavengePadUtils.GetRandomInt()}"));
                    }
                }
                await ctx.SaveChangesAsync();
            }
            return(await GetOperation(dbOperation.Id));
        }
Beispiel #14
0
        public async Task <bool> Connect(Uri peerUri)
        {
            try
            {
                ConnectionLogger?.Invoke($"Establishing connection: {peerUri.OriginalString}");

                await WebSocketClient.Connect(peerUri, ConnectionLogger);

                return(await Task.FromResult(true));
            }
            catch (WebSocketException e)
            {
                Debug.WriteLine($"Caught web socket exception {e.Message}");
                ConnectionLogger?.Invoke(e.Message);
                return(await Task.FromResult(false));
            }
        }
        private async Task TestWebsocketPortable()
        {
            var client = new WebSocketClient();

            client.Opened          += websocket_Opened;
            client.Closed          += websocket_Closed;
            client.MessageReceived += websocket_MessageReceived;

            //Never Ending
            await client.OpenAsync("ws://echo.websocket.org");

            await client.SendAsync("Hello World");

            await client.SendAsync("Hello World2");

            Debug.WriteLine("TestWebsocketPortable");
        }
Beispiel #16
0
        public async Task <bool> OpenRepository(string connectionUri)
        {
            try
            {
                WebSocketConnection = await WebSocketClient.ConnectAsync(new Uri(connectionUri));

                WebSocketConnection.OnMessage += (e, a) => OnMessage(a.Message);
                WebSocketConnection.OnError   += (e, a) => OnError(a.Exception);
                WebSocketConnection.OnClose   += WebSocketConnection_OnClose;
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return(false);
            }
        }
Beispiel #17
0
        public static void BotConnect()
        {
            try
            {
                // Checks if twitch credentials are present
                if (string.IsNullOrEmpty(Settings.Settings.TwAcc) || string.IsNullOrEmpty(Settings.Settings.TwOAuth) || string.IsNullOrEmpty(Settings.Settings.TwChannel))
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        foreach (Window window in Application.Current.Windows)
                        {
                            if (window.GetType() == typeof(MainWindow))
                            {
                                //(window as MainWindow).icon_Twitch.Foreground = new SolidColorBrush(Colors.Red);
                                ((MainWindow)window).LblStatus.Content = "Please fill in Twitch credentials.";
                            }
                        }
                    });
                    return;
                }

                // creates new connection based on the credentials in settings
                ConnectionCredentials credentials   = new ConnectionCredentials(Settings.Settings.TwAcc, Settings.Settings.TwOAuth);
                ClientOptions         clientOptions = new ClientOptions
                {
                    MessagesAllowedInPeriod = 750,
                    ThrottlingPeriod        = TimeSpan.FromSeconds(30)
                };
                WebSocketClient customClient = new WebSocketClient(clientOptions);
                Client = new TwitchClient(customClient);
                Client.Initialize(credentials, Settings.Settings.TwChannel);

                Client.OnMessageReceived += _client_OnMessageReceived;
                Client.OnConnected       += _client_OnConnected;
                Client.OnDisconnected    += _client_OnDisconnected;

                Client.Connect();

                // subscirbes to the cooldowntimer elapsed event for the command cooldown
                CooldownTimer.Elapsed += CooldownTimer_Elapsed;
            }
            catch (Exception)
            {
                Logger.LogStr("Couldn't connect to Twitch, mabe credentials are wrong?");
            }
        }
Beispiel #18
0
        private void twitch_connect()
        {
            ConnectionCredentials credentials = new ConnectionCredentials(TwitchBotName, TwitchBotOauth);
            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 100,
                ThrottlingPeriod        = TimeSpan.FromSeconds(60)
            };
            var customClient = new WebSocketClient(clientOptions);
            var client       = new TwitchClient(customClient);

            client.Initialize(credentials, TwitchBotChannel);
            client.OnGiftedSubscription += giftsub;
            client.OnNewSubscriber      += newsub;
            client.OnReSubscriber       += resub;
            client.Connect();
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            ManualResetEventSlim mr = new ManualResetEventSlim();

            var client = new WebSocketClient(new Uri("ws://localhost:81/"));
            ObservableSoundCapture capture = new ObservableSoundCapture();
            ObservableSpeexEncoder encoder = new ObservableSpeexEncoder(6400);

            capture.Subscribe(encoder);
            var encoderSender = encoder.Select(x => new SenderModel("TestChannel", true, x));

            capture.Start();
            encoderSender.Subscribe(client);
            client.Start();

            mr.Wait();
        }
Beispiel #20
0
        public GdsWebSocketClient(String uri, String userName, string certPath, string pw)
        {
            FileStream f = File.OpenRead(certPath);

            byte[] data = new byte[f.Length];
            f.Read(data, 0, data.Length);
            f.Close();

            this.client   = new WebSocketClient(uri, data, pw);
            this.userName = userName;
            this.password = null;

            client.MessageReceived += Client_MessageReceived;
            client.Disconnected    += Client_Disconnected;

            this.uri = uri;
        }
        public async Task SendLongData_Success()
        {
            using (HttpListener listener = new HttpListener())
            {
                listener.Prefixes.Add(ServerAddress);
                listener.Start();
                Task <HttpListenerContext> serverAccept = listener.GetContextAsync();

                WebSocketClient  client        = new WebSocketClient();
                Task <WebSocket> clientConnect = client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None);

                HttpListenerContext serverContext = await serverAccept;
                Assert.True(serverContext.Request.IsWebSocketRequest);
                HttpListenerWebSocketContext serverWebSocketContext = await serverContext.AcceptWebSocketAsync(null, 0xFFFF, TimeSpan.FromMinutes(100));

                WebSocket clientSocket = await clientConnect;

                byte[] orriginalData = Encoding.UTF8.GetBytes(new string('a', 0x1FFFF));
                await clientSocket.SendAsync(new ArraySegment <byte>(orriginalData), WebSocketMessageType.Text, true, CancellationToken.None);

                byte[] serverBuffer           = new byte[orriginalData.Length];
                WebSocketReceiveResult result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment <byte>(serverBuffer), CancellationToken.None);

                int intermediateCount = result.Count;
                Assert.False(result.EndOfMessage);
                Assert.Equal(WebSocketMessageType.Text, result.MessageType);

                result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment <byte>(serverBuffer, intermediateCount, orriginalData.Length - intermediateCount), CancellationToken.None);

                intermediateCount += result.Count;
                Assert.False(result.EndOfMessage);
                Assert.Equal(WebSocketMessageType.Text, result.MessageType);

                result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment <byte>(serverBuffer, intermediateCount, orriginalData.Length - intermediateCount), CancellationToken.None);

                intermediateCount += result.Count;
                Assert.True(result.EndOfMessage);
                Assert.Equal(orriginalData.Length, intermediateCount);
                Assert.Equal(WebSocketMessageType.Text, result.MessageType);

                Assert.Equal(orriginalData, serverBuffer);

                clientSocket.Dispose();
            }
        }
        /// <exception cref="InvalidOperationException">The client must be logged in before connecting.</exception>
        /// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
        internal override async Task ConnectInternalAsync()
        {
            if (LoginState != LoginState.LoggedIn)
                throw new InvalidOperationException("The client must be logged in before connecting.");
            if (WebSocketClient == null)
                throw new NotSupportedException("This client is not configured with WebSocket support.");

            RequestQueue.ClearGatewayBuckets();

            //Re-create streams to reset the zlib state
            _compressed?.Dispose();
            _decompressor?.Dispose();
            _compressed = new MemoryStream();
            _decompressor = new DeflateStream(_compressed, CompressionMode.Decompress);

            ConnectionState = ConnectionState.Connecting;
            try
            {
                _connectCancelToken?.Dispose();
                _connectCancelToken = new CancellationTokenSource();
                if (WebSocketClient != null)
                    WebSocketClient.SetCancelToken(_connectCancelToken.Token);

                if (!_isExplicitUrl)
                {
                    var gatewayResponse = await GetGatewayAsync().ConfigureAwait(false);
                    _gatewayUrl = $"{gatewayResponse.Url}?v={DiscordConfig.APIVersion}&encoding={DiscordSocketConfig.GatewayEncoding}&compress=zlib-stream";
                }

#if DEBUG_PACKETS
                Console.WriteLine("Connecting to gateway: " + _gatewayUrl);
#endif

                await WebSocketClient.ConnectAsync(_gatewayUrl).ConfigureAwait(false);

                ConnectionState = ConnectionState.Connected;
            }
            catch
            {
                if (!_isExplicitUrl)
                    _gatewayUrl = null; //Uncache in case the gateway url changed
                await DisconnectInternalAsync().ConfigureAwait(false);
                throw;
            }
        }
        public async Task ReceiveFragmentedData_Success()
        {
            var orriginalData = Encoding.UTF8.GetBytes("Hello World");

            using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
            {
                Assert.True(context.WebSockets.IsWebSocketRequest);
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                await webSocket.SendAsync(new ArraySegment <byte>(orriginalData, 0, 2), WebSocketMessageType.Binary, false, CancellationToken.None);
                await webSocket.SendAsync(new ArraySegment <byte>(orriginalData, 2, 2), WebSocketMessageType.Binary, false, CancellationToken.None);
                await webSocket.SendAsync(new ArraySegment <byte>(orriginalData, 4, 7), WebSocketMessageType.Binary, true, CancellationToken.None);
            }))
            {
                var client = new WebSocketClient();
                using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
                {
                    var clientBuffer = new byte[orriginalData.Length];
                    var result       = await clientSocket.ReceiveAsync(new ArraySegment <byte>(clientBuffer), CancellationToken.None);

                    Assert.False(result.EndOfMessage);
                    Assert.Equal(2, result.Count);
                    int totalReceived = result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    result = await clientSocket.ReceiveAsync(
                        new ArraySegment <byte>(clientBuffer, totalReceived, clientBuffer.Length - totalReceived), CancellationToken.None);

                    Assert.False(result.EndOfMessage);
                    Assert.Equal(2, result.Count);
                    totalReceived += result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    result = await clientSocket.ReceiveAsync(
                        new ArraySegment <byte>(clientBuffer, totalReceived, clientBuffer.Length - totalReceived), CancellationToken.None);

                    Assert.True(result.EndOfMessage);
                    Assert.Equal(7, result.Count);
                    totalReceived += result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    Assert.Equal(orriginalData, clientBuffer);
                }
            }
        }
        public Bot(string channel, string token, string Username, List <command> commandList, List <sfx> sfxList, LiteDB.ILiteCollection <counter> countersCol, LiteDB.ILiteCollection <swearJarAcc> accountsColl, List <string> ctList, bool requireModBool, bool quoteBool, bool isPrettyBool, bool coinBool, bool diceBool, int pretyInt, bool sjBool, float sjDenom, bool dadJ)
        {
            countersList = ctList;
            counters     = countersCol;
            commands     = commandList;
            sfxes        = sfxList;
            quote        = quoteBool;
            requireMod   = requireModBool;
            pretty       = isPrettyBool;
            dice         = diceBool;
            coin         = coinBool;
            swearJar     = sjBool;
            pretyIntVal  = pretyInt;
            accounts     = accountsColl;
            dadBool      = dadJ;


            denomination = sjDenom;
            if (Username == "")
            {
                Username = "******";
            }
            if (token == "")
            {
                token = "oauth:x64c6vsc9pfxnajwp16slxhusuiy9e";
            }
            ConnectionCredentials credentials = new ConnectionCredentials(Username, token);

            WebSocketClient customClient = new WebSocketClient();

            client = new TwitchClient(customClient);
            client.Initialize(credentials, channel);

            client.OnLog             += Client_OnLog;
            client.OnJoinedChannel   += Client_OnJoinedChannel;
            client.OnMessageReceived += Client_OnMessageReceived;
            //client.OnWhisperReceived += Client_OnWhisperReceived;
            //client.OnNewSubscriber += Client_OnNewSubscriber;
            client.OnConnected       += Client_OnConnected;
            client.OnDisconnected    += Client_OnDisconnected;
            client.OnConnectionError += onConnectionError;


            client.Connect();
        }
Beispiel #25
0
		async void OnLogin_Clicked(object sender, EventArgs args)
		{			
			loadingDialog = UserDialogs.Instance.Loading("Connecting...",null,null,false,MaskType.Gradient);

			if (String.IsNullOrEmpty(webSocketUrl.Text))
			{
				await DisplayAlert("Validation Error", "Server URL is required", "Re-try");
			}
			else 
			{
				//if(false){
				if (String.IsNullOrEmpty (username.Text) || String.IsNullOrEmpty (password.Text)) {
					await DisplayAlert ("Validation Error", "Username and Password are required", "Re-try");
				} else {
					await App.Database.Delete_RemoteData_Item ();
					await App.Database.Delete_All_Login_Username_Show_For_Del ();
					loadingDialog.Show ();

					//System.Threading.Tasks.Task.Run (() => 
					//{
							ws_client = new WebSocketClient ();
							ws_client.Opened += websocket_Opened;
							ws_client.Closed += websocket_Closed;
							ws_client.MessageReceived += websocket_MessageReceived;		
							//ws_client.AutoSendPongResponse = true;
					//});



					try 
					{
						Debug.WriteLine ("Websocket Opening.....");
						await ws_client.OpenAsync(webSocketUrl.Text);

					} catch (Exception ex) {
						Debug.WriteLine (ex.ToString());
						Debug.WriteLine ("OpenAsync Exception");
						UserDialogs.Instance.ShowError ("Can not Connect to Websocket Server");
					}
				}

			}


		}
Beispiel #26
0
        public Task Send_Start_ReceiveDataOnMutation()
        {
            SnapshotFullName snapshotName = Snapshot.FullName();

            return(TryTest(async() =>
            {
                // arrange
                using TestServer testServer = CreateStarWarsServer();
                WebSocketClient client = CreateWebSocketClient(testServer);
                WebSocket webSocket = await ConnectToServerAsync(client);

                DocumentNode document = Utf8GraphQLParser.Parse(
                    "subscription { onReview(episode: NEW_HOPE) { stars } }");

                var request = new GraphQLRequest(document);

                const string subscriptionId = "abc";

                // act
                await webSocket.SendSubscriptionStartAsync(subscriptionId, request);

                // assert
                await testServer.SendPostRequestAsync(new ClientQueryRequest
                {
                    Query = @"
                            mutation {
                                createReview(episode: NEW_HOPE review: {
                                    commentary: ""foo""
                                    stars: 5
                                }) {
                                    stars
                                }
                            }"
                });

                IReadOnlyDictionary <string, object> message =
                    await WaitForMessage(
                        webSocket,
                        MessageTypes.Subscription.Data,
                        TimeSpan.FromSeconds(15));

                Assert.NotNull(message);
                Snapshot.Match(message, snapshotName);
            }));
        }
Beispiel #27
0
        public async Task InvokeAsync(HttpContext context)
        {
            //验证请求地址
            if (TenantPathCache.Match(context.Request.Path))
            {
                //验证是否为websocket请求
                if (context.WebSockets.IsWebSocketRequest)
                {
                    //获取当前租户的配置信息
                    var webSocketOption = await socketOptionFactory.GetAsync(context.Request.Path);

                    //获取buff接收大小
                    ReciveBuffSize = webSocketOption.MaximumReceiveMessageSize;
                    //授权验证
                    foreach (var item in webSocketOption.AuthorizationFilters)
                    {
                        if ((await item.AuthorizationAsync(context)) == false)
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            return;
                        }
                    }
                    //获取传递的连接Id
                    var connectionId = context.Request.Query[RequestQuery.ConnectionId.ToString()];
                    //接收websocket客户端
                    var webSocketClient = new WebSocketClient
                    {
                        WebSocket    = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false),
                        ConnectionId = connectionId.Any() ? connectionId.ToString() : Guid.NewGuid().ToString(),
                        Context      = context
                    };
                    //处理
                    await Handler(context, webSocketClient).ConfigureAwait(false);
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    logger.LogWarning("当前不是一个有效的webscoket连接");
                }
            }
            else
            {
                await next(context);
            }
        }
        /// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
        internal override async Task DisconnectInternalAsync(Exception ex = null)
        {
            if (WebSocketClient == null)
                throw new NotSupportedException("This client is not configured with WebSocket support.");

            if (ConnectionState == ConnectionState.Disconnected) return;
            ConnectionState = ConnectionState.Disconnecting;

            try { _connectCancelToken?.Cancel(false); }
            catch { }

            if (ex is GatewayReconnectException)
                await WebSocketClient.DisconnectAsync(4000).ConfigureAwait(false);
            else
                await WebSocketClient.DisconnectAsync().ConfigureAwait(false);

            ConnectionState = ConnectionState.Disconnected;
        }
Beispiel #29
0
        ///<summary>
        /// Class Constructor that handles the Gazetracker client and the WebSocket connections.
        /// </summary>
        public WSClient()
        {
            createXml();
            wsClient = new WebSocketClient("ws://ciman.math.unipd.it:8000/")
            {
                OnConnected        = OnConnected,
                OnDisconnect       = OnDisconnect,
                OnFailedConnection = OnFailedConnection,
                OnReceive          = OnReceive
            };
            gtClient = new GazeTrackerClient.Client();

            gtClient.ErrorOccured += OnErrorOccured;

            gtClient.Calibration.OnPointChange += new GazeTrackerClient.Calibration.PointChangeHandler(OnCalibrationPointChange);
            gtClient.Calibration.OnEnd         += new GazeTrackerClient.Calibration.EndHandler(OnCalibrationEnd);
            gtClient.GazeData.OnGazeData       += new GazeTrackerClient.GazeData.GazeDataHandler(OnGazeData);
        }
        static void Main()
        {
            var client = new WebSocketClient();
            client.MessageReceived += m =>
            {
                if (m.IsText)
                    Console.WriteLine("RESPONSE: {0}", m.ToString());
            };
            client.OpenAsync("wss://echo.websocket.org").Wait();

            Console.WriteLine("Client connected, enter text and send it with pressing <ENTER>");
            var text = Console.ReadLine();
            while (!string.IsNullOrEmpty(text))
            {
                client.SendAsync(text);
                text = Console.ReadLine();
            }
        }        
Beispiel #31
0
        public async Task WebSocketClient_AcceptsAnyUrl()
        {
            Exception       result = null;
            WebSocketClient reader = null;

            try
            {
                var webSocketClient = new WebSocketClient("fakeurl");
                reader = webSocketClient;
            }
            catch (Exception ex)
            {
                result = ex;
            }

            reader.Dispose();
            Assert.Null(result);
        }
        public void StressTest1()
        {
            var waitEvent = new AutoResetEvent(false);

            var server = new WebSocketServer(8080);
            server.OnReceive += Receive;
            server.Start();

            WebSocketClient socket = new WebSocketClient("ws://localhost:8080/");
            socket.Connect();

            countdownEvent = new CountdownEvent(Messages);
            for (var i = 0; i < Messages; i++)
                ThreadPool.QueueUserWorkItem(DoSend, socket);

            countdownEvent.Wait(new TimeSpan(0, 0, 120));
            Assert.AreEqual(0, countdownEvent.CurrentCount);
        }
        public void Execute(WebSocketClient SocketClient, MessageObject Data)
        {
            var message = Convert.ToString(Data.Body["message"]);

            if (message.Contains('<') || message.Contains('>'))
            {
                SocketClient.Send(new ErrorHandler("Chat message can't contain special characters"));
                return;
            }

            if (!SocketClient.Game.HasStarted)
            {
                SocketClient.Send(new ErrorHandler("Game hasn't started"));
                return;
            }

            SocketClient.Game.SendToPlayers(new ReceiveMessageHandler(SocketClient.Nickname, message, DateTime.Now.ToString("HH:mm:ss")));
        }
Beispiel #34
0
        public async Task HeartbeatLoop(int inter)
        {
            while (_heartbeat)
            {
                await Task.Delay(inter).ConfigureAwait(false);

                if (WebSocketClient.State == WebSocketState.Open)
                {
                    PingStopwatch.Reset();
                    PingStopwatch.Start();
                    WebSocketClient.Send(@"{""op"":1, ""t"":null,""d"":null,""s"":null}");
                }
                else
                {
                    break;
                }
            }
        }
Beispiel #35
0
        public M2Bot(IOptions <TwitchConfig> twitchOptions,
                     IEnumerable <IChatCommand> chatCommands,
                     ILogger <M2Bot> logger)
        {
            _twitchConfig = twitchOptions.Value;
            _chatCommands = chatCommands;
            _logger       = logger;

            var twitchClientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };

            var socketClient = new WebSocketClient(twitchClientOptions);

            _client = new TwitchClient(socketClient);
        }
Beispiel #36
0
        private void SetupWebSocketConnection(string botId, string botPassword)
        {
            if (!_useWebSockets)
            {
                return;
            }
            Connector.Authentication.MicrosoftAppCredentials appCredentials = new Connector.Authentication.MicrosoftAppCredentials(botId, botPassword);
            var authHeaders = new Dictionary <string, string>()
            {
                { "authorization", $"Bearer {appCredentials.GetTokenAsync().Result}" }, { "channelid", "emulator" }
            };

            // Bots hosted on Azure will require the authHeaders be passed in as the third argument below. For local testing they are optional and may cause undesired behavior.
            // Setting the channelId to emulator causes the BotFrameworkAdapter in the target bot to treat activities differently. Search for the string 'emulator' in
            // the BotBuilder repo to learn more.
            _webSocketClient = new WebSocketClient(this._TargetBotEndPoint, _handler, null);
            _webSocketClient.ConnectAsync(authHeaders).Wait();
        }
        public TwitchChatBot(
            IOptionsMonitor <TwitchSettings> optionsMonitor,
            ILogger <TwitchChatBot> logger
            )
        {
            _logger = logger;
            var credentials   = new ConnectionCredentials("raw_coding", optionsMonitor.CurrentValue.AccessToken);
            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };
            var customClient = new WebSocketClient(clientOptions);

            _client = new(customClient);
            _client.Initialize(credentials, "raw_coding");
            _client.OnLog += Client_OnLog;
        }
        private async Task DisconnectInternalAsync()
        {
            if (ConnectionState == ConnectionState.Disconnected)
            {
                return;
            }
            ConnectionState = ConnectionState.Disconnecting;

            try { _connectCancelToken?.Cancel(false); }
            catch { }

            //Wait for tasks to complete
            await _udp.StopAsync().ConfigureAwait(false);

            await WebSocketClient.DisconnectAsync().ConfigureAwait(false);

            ConnectionState = ConnectionState.Disconnected;
        }
Beispiel #39
0
        /// <summary>
        /// Constructor for a client that interface's with Twitch's PubSub system.
        /// </summary>
        /// <param name="logger">Optional ILogger param to enable logging</param>
        public TwitchPubSub(ILogger <TwitchPubSub> logger = null)
        {
            _logger = logger;

            var options = new ClientOptions {
                ClientType = ClientType.PubSub
            };

            _socket = new WebSocketClient(options);

            _socket.OnConnected    += Socket_OnConnected;
            _socket.OnError        += OnError;
            _socket.OnMessage      += OnMessage;
            _socket.OnDisconnected += Socket_OnDisconnected;

            _pongTimer.Interval = 15000; //15 seconds, we should get a pong back within 10 seconds.
            _pongTimer.Elapsed += PongTimerTick;
        }
Beispiel #40
0
        public void BeginListenTrades(ICollection <ISymbol> symbols)
        {
            var pairs = new List <string>();

            foreach (var symbol in symbols)
            {
                var baseCurrency  = Exchange.GetCurrencyCode(symbol.BaseCurrencyCode);
                var quoteCurrency = Exchange.GetCurrencyCode(symbol.QuoteCurrencyCode);

                pairs.Add($"{baseCurrency}/{quoteCurrency}");
            }

            WebSocketClient.Send(JsonConvert.SerializeObject(new SubscriptionRequest {
                Event = "subscribe", Pair = pairs, Subscription = new BaseEventInnerRequest {
                    Name = "trade"
                }
            }));
        }
        public Bot()
        {
            ConnectionCredentials creds = new ConnectionCredentials(Info.BotUsername, Info.BotToken);
            var clientOptions           = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };
            WebSocketClient customClient = new WebSocketClient(clientOptions);

            client = new TwitchClient(customClient);
            client.Initialize(creds, Info.ChannelName);

            client.OnJoinedChannel   += Client_OnJoinedChannel;
            client.OnMessageReceived += Client_OnMessageReceived;

            client.Connect();
        }
 public async Task NegotiateSubProtocol_Success()
 {
     using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
     {
         Assert.True(context.WebSockets.IsWebSocketRequest);
         Assert.Equal("alpha, bravo, charlie", context.Request.Headers["Sec-WebSocket-Protocol"]);
         var webSocket = await context.WebSockets.AcceptWebSocketAsync("Bravo");
     }))
     {
         var client = new WebSocketClient();
         client.SubProtocols.Add("alpha");
         client.SubProtocols.Add("bravo");
         client.SubProtocols.Add("charlie");
         using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
         {
             Assert.Equal("Bravo", clientSocket.SubProtocol);
         }
     }
 }
        public async Task SendEmptyData_Success()
        {
            using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
            {
                Assert.True(context.WebSockets.IsWebSocketRequest);
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                var serverBuffer = new byte[0];
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(serverBuffer), CancellationToken.None);
                Assert.True(result.EndOfMessage);
                Assert.Equal(0, result.Count);
                Assert.Equal(WebSocketMessageType.Binary, result.MessageType);
            }))
            {
                var client = new WebSocketClient();
                using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
                {
                    var orriginalData = new byte[0];
                    await clientSocket.SendAsync(new ArraySegment<byte>(orriginalData), WebSocketMessageType.Binary, true, CancellationToken.None);
                }
            }
        }
	private void CreateClient(Socket client)
	{
		WebSocketClient wsc = null;

		//証明書がセットされていたら、
		//暗号化モードでクライアントを初期化する。
		if(cert == null)
		{
			wsc = new WebSocketClient(client);
		}else{
			wsc = new WebSocketClient(client,cert);
		}

		wsc.Handshake();
		Task.Run(()=> {wsc.Run();});

		//接続時のイベント起動
		var e = new ClientConnectedEventArgs();
		e.Client = wsc;

		OnClientConnectedHandler(e);
	}
        public async Task TestWebsocketPortable()
        {
            counter = 0;

            var client = new WebSocketClient();
            client.Opened += websocket_Opened;
            client.Closed += websocket_Closed;
            client.MessageReceived += websocket_MessageReceived;

            //Never Ending
            await client.OpenAsync("ws://echo.websocket.org");

            await client.SendAsync("Hello World");

            await client.SendAsync("Hello World2");

            await Task.Delay(500);

            Assert.IsTrue(counter == 2);

            Debug.WriteLine("TestWebsocketPortable");
        }
Beispiel #46
0
        private int receiveWebsocket(byte[] data, uint len, WebSocketClient.WEBSOCKET_PACKET_TYPES opcode, WebSocketClient.WEBSOCKET_RESULT_CODES e)
        {
            string sdata = Encoding.ASCII.GetString(data, 0, (int)len);

            try {
                WSData msg = JsonConvert.DeserializeObject<WSData>(sdata);
                if (msg.type != "nop")
                    debug("websocket receive: " + sdata);

                if (msg.type == "tickle" && msg.subtype == "push")
                    checkPushes();
            } catch (Exception) {
                debug("unknown websocket data received");
            }
            wsCli.ReceiveAsync();

            return 0;
        }
Beispiel #47
0
 private void openWebsocket()
 {
     // wss://stream.pushbullet.com/websocket/<your_access_token_here>
     try {
         wsCli = new WebSocketClient();
         wsCli.SSL = true;
         wsCli.Port = WebSocketClient.WEBSOCKET_DEF_SSL_SECURE_PORT;
         wsCli.URL = "wss://stream.pushbullet.com/websocket/" + apiToken;
         wsCli.ConnectionCallBack = connectWebsocket;
         wsCli.ReceiveCallBack = receiveWebsocket;
         wsCli.ConnectAsync();
     } catch (Exception e) {
         debug("Failed to set up websocket: " + e.Message);
     }
 }
Beispiel #48
0
        private int connectWebsocket(WebSocketClient.WEBSOCKET_RESULT_CODES err)
        {
            debug("websocket error = " + err);
            if (err == WebSocketClient.WEBSOCKET_RESULT_CODES.WEBSOCKET_CLIENT_SUCCESS) {
                online = true;
                debug("Connected");
                wsCli.ReceiveAsync();
            } else {
                online = false;
                debug("WebSocket offline");
            }

            return 0;
        }
Beispiel #49
0
 public WebSocketMessageHandler(ConnectionMaintainer cm)
 {
     this._connectionMaintainer = cm;
     WebSocketClient = new WebSocketClient(this);
     WebSocketServer = new WebSocketServer(this);
 }
        public async Task ReceiveFragmentedData_Success()
        {
            var orriginalData = Encoding.UTF8.GetBytes("Hello World");
            using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
            {
                Assert.True(context.WebSockets.IsWebSocketRequest);
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                await webSocket.SendAsync(new ArraySegment<byte>(orriginalData, 0, 2), WebSocketMessageType.Binary, false, CancellationToken.None);
                await webSocket.SendAsync(new ArraySegment<byte>(orriginalData, 2, 2), WebSocketMessageType.Binary, false, CancellationToken.None);
                await webSocket.SendAsync(new ArraySegment<byte>(orriginalData, 4, 7), WebSocketMessageType.Binary, true, CancellationToken.None);
            }))
            {
                var client = new WebSocketClient();
                using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
                {
                    var clientBuffer = new byte[orriginalData.Length];
                    var result = await clientSocket.ReceiveAsync(new ArraySegment<byte>(clientBuffer), CancellationToken.None);
                    Assert.False(result.EndOfMessage);
                    Assert.Equal(2, result.Count);
                    int totalReceived = result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    result = await clientSocket.ReceiveAsync(
                        new ArraySegment<byte>(clientBuffer, totalReceived, clientBuffer.Length - totalReceived), CancellationToken.None);
                    Assert.False(result.EndOfMessage);
                    Assert.Equal(2, result.Count);
                    totalReceived += result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    result = await clientSocket.ReceiveAsync(
                        new ArraySegment<byte>(clientBuffer, totalReceived, clientBuffer.Length - totalReceived), CancellationToken.None);
                    Assert.True(result.EndOfMessage);
                    Assert.Equal(7, result.Count);
                    totalReceived += result.Count;
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

                    Assert.Equal(orriginalData, clientBuffer);
                }
            }
        }
Beispiel #51
0
        public void SendAndRecieve()
        {
            WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat"));

              ManualResetEvent receiveEvent = new ManualResetEvent(false);
              ws.OnMessage += (s, e) =>
              {
            receiveEvent.Set();
              };

              ws.Connect();
              ws.Send("login: "******"Msg #" + i);
            received = receiveEvent.WaitOne(TimeSpan.FromSeconds(2));
            Assert.IsTrue(received, "Fail on round " + i);
              }

              receiveEvent.Close();

              ws.Close();
        }
Beispiel #52
0
 public void Send()
 {
     WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat"));
       ws.Connect();
       ws.Send("login: User1");
       ws.Close();
 }
        /// <summary>
        /// The Following Three Methods are for the Websocket
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        public static int SendCallback(WebSocketClient.WEBSOCKET_RESULT_CODES error)
        {
            try
            {
                ret = wsc.ReceiveAsync();
            }
            catch (Exception e)
            {
                return -1;
            }

            return 0;
        }
        public async Task CloseFromCloseReceived_Success()
        {
            string closeDescription = "Test Closed";
            using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
            {
                Assert.True(context.WebSockets.IsWebSocketRequest);
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, closeDescription, CancellationToken.None);

                var serverBuffer = new byte[1024];
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(serverBuffer), CancellationToken.None);
                Assert.True(result.EndOfMessage);
                Assert.Equal(0, result.Count);
                Assert.Equal(WebSocketMessageType.Close, result.MessageType);
                Assert.Equal(WebSocketCloseStatus.NormalClosure, result.CloseStatus);
                Assert.Equal(closeDescription, result.CloseStatusDescription);
            }))
            {
                var client = new WebSocketClient();
                using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
                {
                    var clientBuffer = new byte[1024];
                    var result = await clientSocket.ReceiveAsync(new ArraySegment<byte>(clientBuffer), CancellationToken.None);
                    Assert.True(result.EndOfMessage);
                    Assert.Equal(0, result.Count);
                    Assert.Equal(WebSocketMessageType.Close, result.MessageType);
                    Assert.Equal(WebSocketCloseStatus.NormalClosure, result.CloseStatus);
                    Assert.Equal(closeDescription, result.CloseStatusDescription);

                    Assert.Equal(WebSocketState.CloseReceived, clientSocket.State);

                    await clientSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);

                    Assert.Equal(WebSocketState.Closed, clientSocket.State);
                }
            }
        }
Beispiel #55
0
        static void Main(string[] args)
        {
            try
            {
                var config = new WebSocketClientConfiguration();
                //config.SslTargetHost = "Cowboy";
                //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer"));
                //config.SslPolicyErrorsBypassed = true;

                var uri = new Uri("ws://echo.websocket.org/");
                //var uri = new Uri("wss://127.0.0.1:22222/test");
                //var uri = new Uri("ws://127.0.0.1:22222/test");
                _client = new WebSocketClient(uri, config, _log);
                _client.ServerConnected += OnServerConnected;
                _client.ServerDisconnected += OnServerDisconnected;
                _client.ServerTextReceived += OnServerTextReceived;
                _client.ServerBinaryReceived += OnServerBinaryReceived;
                _client.Connect();

                Console.WriteLine("WebSocket client has connected to server [{0}].", uri);
                Console.WriteLine("Type something to send to server...");
                while (_client.State == WebSocketState.Open)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                            break;

                        if (text == "many")
                        {
                            text = new string('x', 1024);
                            Stopwatch watch = Stopwatch.StartNew();
                            int count = 10000;
                            for (int i = 1; i <= count; i++)
                            {
                                _client.SendBinary(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send binary -> Sequence[{1}] -> TextLength[{2}].",
                                    _client.LocalEndPoint, i, text.Length);
                            }
                            watch.Stop();
                            Console.WriteLine("Client [{0}] send binary -> Count[{1}] -> Cost[{2}] -> PerSecond[{3}].",
                                _client.LocalEndPoint, count, watch.ElapsedMilliseconds / 1000, count / (watch.ElapsedMilliseconds / 1000));
                        }
                        else if (text == "big")
                        {
                            text = new string('x', 1024 * 1024 * 100);
                            _client.SendBinary(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text);
                        }
                        else
                        {
                            _client.SendBinary(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text);

                            //_client.SendText(text);
                            //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                _client.Close(WebSocketCloseCode.NormalClosure);
                Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
        public static int ReceiveCallback(byte[] data, uint datalen, WebSocketClient.WEBSOCKET_PACKET_TYPES opcode, WebSocketClient.WEBSOCKET_RESULT_CODES error)
        {
            try
            {
                string s = Encoding.UTF8.GetString(data, 0, data.Length);
                if (s.Contains("push"))
                {
                    getPush();

                }

            }
            catch (Exception e)
            {
                return -1;
            }
            return 0;
        }
        public async Task ReceiveLongDataInLargeBuffer_Success()
        {
            var orriginalData = Encoding.UTF8.GetBytes(new string('a', 0x1FFFF));
            using (var server = KestrelWebSocketHelpers.CreateServer(async context =>
            {
                Assert.True(context.WebSockets.IsWebSocketRequest);
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                await webSocket.SendAsync(new ArraySegment<byte>(orriginalData), WebSocketMessageType.Binary, true, CancellationToken.None);
            }))
            {
                var client = new WebSocketClient() { ReceiveBufferSize = 0xFFFFFF };
                using (var clientSocket = await client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None))
                {
                    var clientBuffer = new byte[orriginalData.Length];
                    var result = await clientSocket.ReceiveAsync(new ArraySegment<byte>(clientBuffer), CancellationToken.None);
                    Assert.True(result.EndOfMessage);
                    Assert.Equal(orriginalData.Length, result.Count);
                    Assert.Equal(WebSocketMessageType.Binary, result.MessageType);
                    Assert.Equal(orriginalData, clientBuffer);
                }
            }
        }
Beispiel #58
0
 public void Connect()
 {
     WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat"));
       ws.Connect();
       ws.Close();
 }
Beispiel #59
0
        private void DoAcceptTcpClient(IAsyncResult ar)
        {
            var callback = ar.AsyncState as MensagemRecebidaCallback;
            bool startAcceptPending = false;

            Interlocked.Increment(ref clientCount);

            if (clientCount < CLIENT_LIMIT)
                StartAccept(callback);
            else
                startAcceptPending = true;

            using (var client = new WebSocketClient(listener.EndAcceptTcpClient(ar), callback)) { };

            Interlocked.Decrement(ref clientCount);

            if(startAcceptPending)
                StartAccept(callback);

        }
        private async Task TestBigString()
        {
            var client = new WebSocketClient();
            client.Opened += websocket_Opened;
            client.Closed += websocket_Closed;
            client.MessageReceived += websocket_MessageReceived;
            client.Error += Client_Error;

            //Never Ending
            await client.OpenAsync("ws://echo.websocket.org");
            

            var sb = new StringBuilder();
            for (int i = 0;i < 1000;i++)
            {
                sb.Append("A");
            }

            for (int i = 0; i < 5; i++)
            {
                await client.SendAsync(sb.ToString());

            }
            await Task.Delay(1000);

            await client.CloseAsync();

            await Task.Delay(100);

            Debug.WriteLine("TestWebsocketPortable");
        }