SendAsync() public method

public SendAsync ( System buffer, System messageType, bool endOfMessage, System cancellationToken ) : System.Threading.Tasks.Task
buffer System
messageType System
endOfMessage bool
cancellationToken System
return System.Threading.Tasks.Task
Exemplo n.º 1
5
        private void TestWebSockets()
        {
            var socket = new ClientWebSocket();
            Console.WriteLine("Connecting");
            socket.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None).Wait();

            Console.WriteLine("Sending");
            socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), WebSocketMessageType.Text, true, CancellationToken.None).Wait();

            var buffer = new byte[1024];
            Console.WriteLine("Receiving");
            var result = socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

            Console.WriteLine($"Recieved: {Encoding.UTF8.GetString(buffer, 0, result.Count)}");
        }
Exemplo n.º 2
0
        public async Task SendMessageAsync(string text, CancellationToken cancellationToken)
        {
            if (_ws == null)
            {
                throw new InvalidSocketStateException("Faild to emit, websocket is not connected yet.");
            }
            if (_ws.State != WebSocketState.Open)
            {
                throw new InvalidSocketStateException("Connection is not open.");
            }

            byte[] bytes = Encoding.UTF8.GetBytes(text);
            try
            {
                await _ws.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, cancellationToken);

#if DEBUG
                Trace.WriteLine($"⬆ {DateTime.Now} {text}");
#endif
            }
            catch (TaskCanceledException)
            {
#if DEBUG
                Trace.WriteLine($"❌ {DateTime.Now} Cancel \"{text}\"");
#endif
            }
        }
        public async Task SendMessageAsync(string text)
        {
            if (_ws == null)
            {
                throw new InvalidOperationException("Faild to emit, websocket is not connected yet.");
            }
            if (_ws.State != WebSocketState.Open)
            {
                throw new Exception("Connection is not open.");
            }

            var messageBuffer = Encoding.UTF8.GetBytes(text);
            var messagesCount = (int)Math.Ceiling((double)messageBuffer.Length / SendChunkSize);

            for (var i = 0; i < messagesCount; i++)
            {
                var offset      = (SendChunkSize * i);
                var count       = SendChunkSize;
                var lastMessage = ((i + 1) == messagesCount);

                if ((count * (i + 1)) > messageBuffer.Length)
                {
                    count = messageBuffer.Length - offset;
                }

                await _ws.SendAsync(new ArraySegment <byte>(messageBuffer, offset, count), WebSocketMessageType.Text, lastMessage, _connectionToken.Token);
            }
#if DEBUG
            Trace.WriteLine($"⬆ {DateTime.Now} {text}");
#endif
        }
Exemplo n.º 4
0
        public async Task WebsocketBasic(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, WebsocketBasicConfiguration);

                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(applicationUrl.Replace("http://", "ws://")), CancellationToken.None);

                    var receiveBody = new byte[100];

                    for (int i = 0; i < 4; i++)
                    {
                        var message = "Message " + i.ToString();
                        byte[] sendBody = Encoding.UTF8.GetBytes(message);
                        await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
                        var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);

                        Assert.Equal(WebSocketMessageType.Text, receiveResult.MessageType);
                        Assert.True(receiveResult.EndOfMessage);
                        Assert.Equal(sendBody.Length, receiveResult.Count);
                        Assert.Equal(message, Encoding.UTF8.GetString(receiveBody, 0, receiveResult.Count));
                    }
                }
            }
        }
Exemplo n.º 5
0
        public async void TestConnectWebSocket()
        {
            if (TestHelper.IsMono)
            {
                Assert.Inconclusive("Mono doesn't have support to WebSockets");
            }

            Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");

            Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");

            var clientSocket = new ClientWebSocket();
            var ct = new CancellationTokenSource();
            await clientSocket.ConnectAsync(new Uri(Resources.WsServerAddress + "/test"), ct.Token);

            Assert.AreEqual(clientSocket.State, WebSocketState.Open, "Connection is open");

            var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
            var buffer = new ArraySegment<byte>(new byte[1024]);

            await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
            var result = await clientSocket.ReceiveAsync(buffer, ct.Token);

            Assert.IsTrue(result.EndOfMessage);
            Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME");
        }
        public static async Task RunSample()
        {
            ClientWebSocket websocket = new ClientWebSocket();

            string url = "ws://localhost:5000/";
            Console.WriteLine("Connecting to: " + url);
            await websocket.ConnectAsync(new Uri(url), CancellationToken.None);

            string message = "Hello World";
            Console.WriteLine("Sending message: " + message);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await websocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] incomingData = new byte[1024];
            WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);

            if (result.CloseStatus.HasValue)
            {
                Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
            }
            else
            {
                Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
            }
        }
Exemplo n.º 7
0
        public void TestMethod1()
        {
            var total = 10000;
            var msg = "hello";
            var client = new ClientWebSocket();
            client.ConnectAsync(new Uri("ws://localhost:8889/ws.axd"), CancellationToken.None).Wait();
            client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(total.ToString())), WebSocketMessageType.Text, true, CancellationToken.None).Wait();
            client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg)), WebSocketMessageType.Text, true, CancellationToken.None).Wait();

            var w = new Stopwatch();
            w.Start();
            ReceiveMessages(client, msg, total).Wait();
            w.Stop();
            Trace.WriteLine(w.ElapsedMilliseconds);

            while (_counter < total) Thread.Sleep(10);
        }
Exemplo n.º 8
0
        internal void send(String text)
        {
            if (!isConnected())
            {
                throw new Exception("WebSocket is not open");
            }

            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(text);
                ArraySegment <byte>         segment = new ArraySegment <byte>(buffer);
                System.Threading.Tasks.Task t       = clientWebSocket.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
                t.Wait();
            }
            catch (System.Net.WebSockets.WebSocketException)
            {
                //TODO:
            }
        }
Exemplo n.º 9
0
        public static async Task Send(ClientWebSocket websocket)
        {
            string message = "Hello World";
            //Console.WriteLine("Sending message: " + message);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await websocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] incomingData = new byte[1024];
            WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
        }
Exemplo n.º 10
0
 public Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
 {
     if (webSocket.State == WebSocketState.Open)
     {
         return(webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken));
     }
     else
     {
         return(Task.CompletedTask);
     }
 }
        /// <summary>
        /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
        /// on that response. Implement this method in a partial class to enable this behavior
        /// </summary>
        /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
        /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IContainerExecResponse"
        /// /> from the remote call</param>
        /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
        /// immediately (set to true to skip further processing )</param>
        partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task <Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IContainerExecResponse> response, ref global::System.Threading.Tasks.Task <bool> returnNow)
        {
            var containerExecResponse = response.ConfigureAwait(false).GetAwaiter().GetResult();

            socket = new System.Net.WebSockets.ClientWebSocket();
            // Connect websocket
            socket.ConnectAsync(new System.Uri(containerExecResponse.WebSocketUri), _cancellationTokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();
            socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(containerExecResponse.Password)), WebSocketMessageType.Text, true, _cancellationTokenSource.Token).ConfigureAwait(false).GetAwaiter().GetResult();

            var receiver = PullResponse();
            var sender   = PushCommand();

            Task.WaitAll(sender, receiver);
            returnNow = global::System.Threading.Tasks.Task.FromResult(true);
        }
Exemplo n.º 12
0
        private static async Task Send(ClientWebSocket webSocket)
        {
            var random = new Random();
            byte[] buffer = new byte[sendChunkSize];

            while (webSocket.State == WebSocketState.Open)
            {
                random.NextBytes(buffer);

                await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, false, CancellationToken.None);
                LogStatus(false, buffer, buffer.Length);
   
                await Task.Delay(delay);
            }
        }
Exemplo n.º 13
0
 private async System.Threading.Tasks.Task Send(string msg, int timeout)
 {
     try
     {
         using (var cts = new System.Threading.CancellationTokenSource(timeout))
         {
             var segment = new System.ArraySegment <byte>(System.Text.Encoding.UTF8.GetBytes(msg));
             await ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, cts.Token);
         }
     }
     catch (System.Threading.Tasks.TaskCanceledException)
     {
         throw new TimeoutException("Timeout when sending message.");
     }
 }
Exemplo n.º 14
0
        static async Task Run()
        {
            var ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri("ws://localhost:8088"), CancellationToken.None);

            
            byte[] buf = new byte[4096];
            var seg = new ArraySegment<byte>(buf, 0, buf.Length);
            var r1 = await ws.ReceiveAsync(seg, CancellationToken.None);
            string id = UTF8Encoding.UTF8.GetString(buf, 0, r1.Count);
            Console.WriteLine("SessionId=" + id);

            for (int i = 0; i < 20; i++)
            {
                var msg = UTF8Encoding.UTF8.GetBytes("Send(" + i + ")");
                await ws.SendAsync(new ArraySegment<byte>(msg, 0, msg.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                var rcv = await ws.ReceiveAsync(seg, CancellationToken.None);
                string response = UTF8Encoding.UTF8.GetString(buf, 0, rcv.Count);
                Console.WriteLine("Response=" + response);
                Thread.Sleep(2000);
            }
        }
 private Task PushCommand()
 {
     return(Task.Factory.StartNew(async() =>
     {
         StringBuilder input = new StringBuilder();
         // Loop until input is entered.
         while (socket.State == WebSocketState.Open && !this._cancellationTokenSource.Token.IsCancellationRequested)
         {
             if (Console.KeyAvailable)
             {
                 var key = Console.ReadKey(false);
                 input.Append(key.KeyChar);
                 if (key.Key == ConsoleKey.Enter)
                 {
                     _ = socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(input.ToString())), WebSocketMessageType.Text, true, this._cancellationTokenSource.Token);
                     input.Clear();
                 }
             }
             System.Threading.Thread.Sleep(250);
         }
     }, this._cancellationTokenSource.Token));
 }
Exemplo n.º 16
0
        public void AuthorizationTest()
        {
            using (WebApp.Start(new StartOptions("http://localhost:8989"), startup =>
            {
                startup.MapOwinFleckRoute("/fleck", connection =>
                {
                    var id = ConfigureIntegrationTestConnectionAndGetId(connection);
                    
                    connection.OnAuthenticateRequest = () =>
                    {
                        var result = id % 2 == 1;
                        Send(id, $"Auth {id}: {result}");
                        return result;
                    };

                });
            }))
            using (var client1 = new ClientWebSocket())
            using (var client2 = new ClientWebSocket())
            using (var client3 = new ClientWebSocket())
            {
                client1.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();
                
                try
                {
                    client2.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();
                    Assert.Fail("Client 2 should not be unauthorized");
                }
                catch (AggregateException ex)
                {
                    Assert.AreEqual("Unable to connect to the remote server", ex.InnerException.Message);
                }
                
                client3.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();

                var bytes3 = new byte[1024];
                var segment3 = new ArraySegment<byte>(bytes3);
                var receive3 = client3.ReceiveAsync(segment3, CancellationToken.None);

                var message1 = "Hello world";
                var bytes1 = Encoding.UTF8.GetBytes(message1);
                var segment1 = new ArraySegment<byte>(bytes1);
                client1.SendAsync(segment1, WebSocketMessageType.Text, true, CancellationToken.None).Wait();

                var result3 = receive3.Result;
                Assert.AreEqual(WebSocketMessageType.Text, result3.MessageType);
                var message3 = Encoding.UTF8.GetString(segment3.Array, 0, result3.Count);
                Assert.AreEqual(message3, "User 1: Hello world");

                client3.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
                client3.Dispose();
                Task.Delay(100).Wait();

                client1.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
                client1.Dispose();
                Task.Delay(100).Wait();
            }

            var messages = DequeueMessages();
            Assert.AreEqual(8, messages.Count);
            Assert.AreEqual("Auth 1: True", messages[0]);
            Assert.AreEqual("Open: 1", messages[1]);
            Assert.AreEqual("Auth 2: False", messages[2]);
            Assert.AreEqual("Auth 3: True", messages[3]);
            Assert.AreEqual("Open: 3", messages[4]);
            Assert.AreEqual("User 1: Hello world", messages[5]);
            Assert.AreEqual("Close: 3", messages[6]);
            Assert.AreEqual("Close: 1", messages[7]);
        }
Exemplo n.º 17
0
 public void RespondToMicrosoftWebSocketClient()
 {
     using(var socket = new ClientWebSocket())
     {
         socket.ConnectAsync(new Uri("ws://127.0.0.1:20000/"), CancellationToken.None).Wait(1000);
         var buffer = Encoding.UTF8.GetBytes("abcdefg");
         socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None).Wait(1000);
         var receiveBuffer = ClientWebSocket.CreateClientBuffer(1024, 1024);
         var result = socket.ReceiveAsync(receiveBuffer, CancellationToken.None);
         result.Wait(1000);
         var msg = Encoding.UTF8.GetString(receiveBuffer.Array, 0, result.Result.Count);
         Assert.AreEqual("gfedcba", msg);
     }            
 }
        private static async void Subscribe(string product, Action<RealtimeMessage> onMessageReceived)
        {
            if (String.IsNullOrWhiteSpace(product))
                throw new ArgumentNullException("product");

            if (onMessageReceived == null)
                throw new ArgumentNullException("onMessageReceived", "Message received callback must not be null.");

            var uri = new Uri("wss://ws-feed.exchange.coinbase.com");
            var webSocketClient = new ClientWebSocket();
            var cancellationToken = new CancellationToken();
            var requestString = String.Format(@"{{""type"": ""subscribe"",""product_id"": ""{0}""}}", product);
            var requestBytes = UTF8Encoding.UTF8.GetBytes(requestString);
            await webSocketClient.ConnectAsync(uri, cancellationToken);

            if (webSocketClient.State == WebSocketState.Open)
            {
                var subscribeRequest = new ArraySegment<byte>(requestBytes);
                var sendCancellationToken = new CancellationToken();
                await webSocketClient.SendAsync(subscribeRequest, WebSocketMessageType.Text, true, sendCancellationToken);

                while (webSocketClient.State == WebSocketState.Open)
                {
                    var receiveCancellationToken = new CancellationToken();
                    var receiveBuffer = new ArraySegment<byte>(new byte[1024 * 1024 * 5]); // 5MB buffer
                    var webSocketReceiveResult = await webSocketClient.ReceiveAsync(receiveBuffer, receiveCancellationToken);
                    if (webSocketReceiveResult.Count == 0) continue;

                    var jsonResponse = Encoding.UTF8.GetString(receiveBuffer.Array, 0, webSocketReceiveResult.Count);
                    var jToken = JToken.Parse(jsonResponse);

                    var typeToken = jToken["type"];
                    if (typeToken == null) continue;

                    var type = typeToken.Value<string>();
                    RealtimeMessage realtimeMessage = null;

                    switch (type)
                    {
                        case "received":
                            realtimeMessage = new RealtimeReceived(jToken);
                            break;
                        case "open":
                            realtimeMessage = new RealtimeOpen(jToken);
                            break;
                        case "done":
                            realtimeMessage = new RealtimeDone(jToken);
                            break;
                        case "match":
                            realtimeMessage = new RealtimeMatch(jToken);
                            break;
                        case "change":
                            realtimeMessage = new RealtimeChange(jToken);
                            break;
                        default:
                            break;
                    }

                    if (realtimeMessage == null)
                        continue;

                    onMessageReceived(realtimeMessage);
                }
            }
        }
Exemplo n.º 19
0
 private static async Task send(ClientWebSocket ws, object message)
 {
     await ws.SendAsync(new ArraySegment<byte>(Serializer.Serialize(message)), WebSocketMessageType.Binary, true, CancellationToken.None);
 }
Exemplo n.º 20
0
        public async Task EndToEnd_EchoData_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                var accept = (WebSocketAccept)env["websocket.Accept"];
                Assert.NotNull(accept);

                accept(
                    null,
                    async wsEnv =>
                    {
                        var sendAsync = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
                        var receiveAsync = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
                        var closeAsync = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");

                        var buffer = new ArraySegment<byte>(new byte[100]);
                        Tuple<int, bool, int> serverReceive = await receiveAsync(buffer, CancellationToken.None);
                        await sendAsync(new ArraySegment<byte>(buffer.Array, 0, serverReceive.Item3),
                            serverReceive.Item1, serverReceive.Item2, CancellationToken.None);
                        await closeAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    });

                return TaskHelpers.Completed();
            },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);

                    byte[] sendBody = Encoding.UTF8.GetBytes("Hello World");
                    await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
                    var receiveBody = new byte[100];
                    WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);

                    Assert.Equal(WebSocketMessageType.Text, readResult.MessageType);
                    Assert.True(readResult.EndOfMessage);
                    Assert.Equal(sendBody.Length, readResult.Count);
                    Assert.Equal("Hello World", Encoding.UTF8.GetString(receiveBody, 0, readResult.Count));
                }
            }
        }
Exemplo n.º 21
0
        protected void SendIntegrationTestMessages()
        {
            using (var client1 = new ClientWebSocket())
            using (var client2 = new ClientWebSocket())
            {
                client1.ConnectAsync(new Uri("ws://localhost:8989"), CancellationToken.None).Wait();
                Task.Delay(100).Wait();

                client2.ConnectAsync(new Uri("ws://localhost:8989"), CancellationToken.None).Wait();
                Task.Delay(100).Wait();

                var bytes2 = new byte[1024];
                var segment2 = new ArraySegment<byte>(bytes2);
                var receive2 = client2.ReceiveAsync(segment2, CancellationToken.None);

                var message1 = "Hello world";
                var bytes1 = Encoding.UTF8.GetBytes(message1);
                var segment1 = new ArraySegment<byte>(bytes1);
                client1.SendAsync(segment1, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
                Task.Delay(100).Wait();

                var result2 = receive2.Result;
                Assert.AreEqual(WebSocketMessageType.Text, result2.MessageType);
                var message3 = Encoding.UTF8.GetString(segment2.Array, 0, result2.Count);
                Assert.AreEqual("User 1: Hello world", message3);

                client2.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
                client2.Dispose();
                Task.Delay(100).Wait();

                client1.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
                client1.Dispose();
                Task.Delay(100).Wait();
            }
        }
Exemplo n.º 22
0
        public async Task Send(ClientWebSocket webSocket, string stringToSend)
        {
            
            while (webSocket.State == WebSocketState.Open)
            {
               
                Encoding econder = null;

                byte[] buffer = econder.GetBytes(stringToSend);
                await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, false, CancellationToken.None);
                this.SetText("In: " + stringToSend);
                
                await Task.Delay(1000);
            }
        }
Exemplo n.º 23
0
 public Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
 {
     return(webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken));
 }
Exemplo n.º 24
0
        public async Task MessageVerification()
        {
            var snd = "Hello, World!";
            var rcv = string.Empty;
            _echoFactory.OnReceiveAsyncCallBack = (session, buffer, tuple) =>
            {
                var messageLength = tuple.Item3;
                var actual = buffer.Actualize(messageLength);
                

                rcv = Encoding.UTF8.GetString(actual);
                Assert.AreEqual(snd, rcv);
                Trace.WriteLine(string.Format("Message:{0} received on session Id{1}", rcv, session.SessionId), "info");
                return Task.FromResult(0);
            };


            ClientWebSocket clientWSocket = new ClientWebSocket();
            await clientWSocket.ConnectAsync(new Uri(_serverAddressPublish), CancellationToken.None);
            await clientWSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(snd)),
                                          WebSocketMessageType.Text,
                                          true,
                                          CancellationToken.None);



            await Task.Delay(100); // = console.read();
        }
Exemplo n.º 25
0
        public async Task HighFrequencyMessaging_LONGRUNNING()
        {


            var numOfSessions = 100;
            var numOfMessages = 10000;

            var receiveTask = new List<Task<String>>();
            var sendTasks = new List<Task>();

            var clients = new ConcurrentDictionary<string, ClientWebSocket>();
            _echoFactory.OnReceiveAsyncCallBack = (session, buffer, tuple) =>
            {
                var messageLength = tuple.Item3;
                var actual = buffer.Actualize(messageLength);

                var rcv = Encoding.UTF8.GetString(actual);

                // send it back
                session.Post(rcv);
                return Task.FromResult(0);
            };

            Trace.AutoFlush = true;


            int j = 0;
            do
            {

                       var t = Task.Run(async () =>
                                {
                                    var client = new ClientWebSocket();
                                    await client.ConnectAsync(new Uri(_serverAddressPublish), CancellationToken.None);
                                    int k = 0;
                                        while (k < numOfMessages / numOfSessions)
                                        {
                                              Trace.WriteLine(string.Format("Message on client {0}", j));
                                              await client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(j.ToString())),
                                                                                            WebSocketMessageType.Text,
                                                                                            true,
                                                                                            CancellationToken.None);
                                               k++;                                                                   
                                        }
                                        // this exception should never be thrown
                                    clients.AddOrUpdate(Guid.NewGuid().ToString(), client, (key, c) => { throw new Exception("duplicate client!"); });
                                });

                    sendTasks.Add(t);
                j++;
            } while (j < numOfSessions - 1);

            await Task.WhenAll(sendTasks);

            foreach (var client in clients.Values)
                receiveTask.Add(ReceiveFromSocket(client));

            


            await Task.WhenAll(receiveTask);



            /*
            uncomment this if you plan to drain the socket befoire closing., 
            foreach (var client in clients.Values) // be kind rewind
                await client.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "close..", CancellationToken.None);

    */
        }
Exemplo n.º 26
0
        public async Task Echo()
        {
            var snd = "Hello, World!";
            var rcv = string.Empty;

            _echoFactory.OnReceiveAsyncCallBack = (session, buffer, tuple) =>
            {
                var messageLength = tuple.Item3;
                var actual = buffer.Actualize(messageLength);
                

                rcv = Encoding.UTF8.GetString(actual);
                Assert.AreEqual(snd, rcv);

                // send it back
                session.Send(rcv);
                return Task.FromResult(0);
            };


            ClientWebSocket clientWSocket = new ClientWebSocket();
            await clientWSocket.ConnectAsync(new Uri(_serverAddressPublish), CancellationToken.None);

            // send 
            await clientWSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(snd)),
                                          WebSocketMessageType.Text,
                                          true,
                                          CancellationToken.None);



            await Task.Delay(100);
            var socketRecieved = await ReceiveFromSocket(clientWSocket);

            Assert.AreEqual(snd, socketRecieved);
            await clientWSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,  "close",CancellationToken.None);
        }
Exemplo n.º 27
0
        private void RefreshInternal(string debuggerUrl)
        {
            if (string.IsNullOrEmpty(debuggerUrl))
                return;

            ClientWebSocket connection = new ClientWebSocket();
            connection.ConnectAsync(new Uri(debuggerUrl), _token).Wait();

            PageReloadRequest request = new PageReloadRequest();
            string rawRequest = request.ToJson();

            var data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawRequest));
            connection.SendAsync(data, WebSocketMessageType.Text, true, _token).Wait();
            var buffer = new ArraySegment<byte>(new byte[1024]);
            Task<WebSocketReceiveResult> receiveAsync = connection.ReceiveAsync(buffer, _token);
            receiveAsync.Wait();

            string rawResponse = Encoding.UTF8.GetString(buffer.Array, 0, receiveAsync.Result.Count);
            DebugProtocolResponse response = rawResponse.FromJson<DebugProtocolResponse>();

            if (null != response.Error)
            {
                Trace.TraceWarning("Browser returned an error as a response to reload request: {0}",
                                   response.Error.Message);
            }

            connection.Dispose();
        }
Exemplo n.º 28
-1
        public async Task TestConnectWebSocket()
        {
            var wsUrl = Resources.WsServerAddress + "test";
            Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");

            Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");

#if NET46
            var clientSocket = new ClientWebSocket();
            var ct = new CancellationTokenSource();
            await clientSocket.ConnectAsync(new Uri(wsUrl), ct.Token);

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
            var buffer = new ArraySegment<byte>(new byte[1024]);

            await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
            var result = await clientSocket.ReceiveAsync(buffer, ct.Token);

            Assert.IsTrue(result.EndOfMessage, "End of message is true");
            Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME", "Final message is WELCOME");
#else
            var clientSocket = new WebSocket(wsUrl);
            clientSocket.Connect();            

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            clientSocket.Send("HOLA");
            await Task.Delay(100);
#endif
        }