ReceiveAsync() 공개 메소드

public ReceiveAsync ( System buffer, System cancellationToken ) : System.Threading.Tasks.Task
buffer System
cancellationToken System
리턴 System.Threading.Tasks.Task
예제 #1
5
파일: Program.cs 프로젝트: leloulight/dnx
        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)}");
        }
예제 #2
1
        private async Task ListenAsync()
        {
            while (true)
            {
                var buffer       = new byte[ReceiveChunkSize];
                var stringResult = new List <byte>();
                var binaryResult = new List <byte>();
                WebSocketReceiveResult result = null;
                while (_ws.State == WebSocketState.Open)
                {
                    try
                    {
                        //result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _wsWorkTokenSource.Token);
                        result = await _ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Close("io server disconnect");
                            break;
                        }
                        else if (result.MessageType == WebSocketMessageType.Text)
                        {
                            stringResult.AddRange(buffer.Take(result.Count));
                        }
                        else if (result.MessageType == WebSocketMessageType.Binary)
                        {
                            binaryResult.AddRange(buffer.Take(result.Count));
                        }
                        if (result.EndOfMessage)
                        {
                            break;
                        }
                    }
                    catch (WebSocketException e)
                    {
                        Close(e.Message);
                        break;
                    }
                }
                if (result == null)
                {
                    break;
                }
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string message = Encoding.UTF8.GetString(stringResult.ToArray());
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} {message}");
#endif
                    _parser.Unpack(message);
                }
                else if (result.MessageType == WebSocketMessageType.Binary)
                {
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} Binary message");
#endif
                    _io.InvokeBytesReceived(_io.Options.EIO == 4 ? binaryResult.ToArray() : binaryResult.Skip(1).ToArray());
                }
            }
        }
        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));
            }
        }
        private Task PullResponse()
        {
            return(Task.Factory.StartNew(async() =>
            {
                string result = string.Empty;
                var allBytes = new List <byte>();
                while (WebSocketState.Open == socket.State && !this._cancellationTokenSource.Token.IsCancellationRequested)
                {
                    var rcvBuffer = WebSocket.CreateClientBuffer(4096, 4096);
                    WebSocketReceiveResult webSocketReceiveResult = await socket.ReceiveAsync(rcvBuffer, this._cancellationTokenSource.Token);

                    if (null != webSocketReceiveResult)
                    {
                        allBytes.AddRange(new List <byte>(rcvBuffer).GetRange(0, webSocketReceiveResult.Count));
                        if (allBytes.Count > 0 && webSocketReceiveResult.EndOfMessage)
                        {
                            result = Encoding.UTF8.GetString(allBytes.ToArray(), 0, allBytes.Count);
                            Console.Write(result);
                            allBytes.Clear();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(result) && PassThru.ToBool())
                {
                    WriteObject(result.TrimEnd());
                }
            }, this._cancellationTokenSource.Token));
        }
예제 #5
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));
                    }
                }
            }
        }
예제 #6
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");
        }
예제 #7
0
파일: Program.cs 프로젝트: Indifer/Test
        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);
        }
예제 #8
0
        private static async Task startRunner()
        {
            var socketUrl = await getSocketUrl();
            ClientWebSocket ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri($"ws://{socketUrl}"), CancellationToken.None);
            var buffer = new byte[1024 * 10];
            await send(ws, new CreateNewGameRequestSocketMessage() { GameType = "sevens" });

            while (true)
            {
                var segment = new ArraySegment<byte>(buffer);

                var result = await ws.ReceiveAsync(segment, CancellationToken.None);

                switch (result.MessageType)
                {
                    case WebSocketMessageType.Binary:

                        byte[] bytes = new byte[result.Count];
                        Array.ConstrainedCopy(segment.Array, 0, bytes, 0, result.Count);
                        var obj = Serializer.Deserialize(bytes);
                        if (obj is GameStartedSocketMessage)
                        {
                            totalGames++;
                            games++;
                        }
                        else if (obj is AskQuestionSocketMessage)
                        {
                            var answerQ = (AskQuestionSocketMessage)obj;
                            await send(ws, new AnswerQuestionSocketMessage()
                            {
                                AnswerIndex = (short)(answerQ.Answers.Length > 1 ? 1 : 0)
                            });
                            totalAnswers++;
                        }
                        else if (obj is GameOverSocketMessage)
                        {
                            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
                            games--;
                            return;
                        }

                        break;
                    case WebSocketMessageType.Close:
                        await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }


            }

        }
예제 #9
0
        private async Task ListenAsync()
        {
            var buffer = new byte[ReceiveChunkSize];

            try
            {
                while (_ws.State == WebSocketState.Open)
                {
                    var stringResult = new StringBuilder();
                    var binaryResult = new List <byte>();
                    WebSocketReceiveResult result;
                    do
                    {
                        result = await _ws.ReceiveAsync(new ArraySegment <byte>(buffer), _connectionToken.Token);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Close();
                        }
                        else if (result.MessageType == WebSocketMessageType.Text)
                        {
                            string str = Encoding.UTF8.GetString(buffer, 0, result.Count);
                            stringResult.Append(str);
                        }
                        else if (result.MessageType == WebSocketMessageType.Binary)
                        {
                            binaryResult.AddRange(buffer.Take(result.Count));
                        }
                    } while (!result.EndOfMessage);
                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        string message = stringResult.ToString();
#if DEBUG
                        Trace.WriteLine($"⬇ {DateTime.Now} {message}");
#endif
                        _parser.Unpack(message);
                    }
                    else if (result.MessageType == WebSocketMessageType.Binary)
                    {
#if DEBUG
                        var builder = new StringBuilder();
                        binaryResult.ForEach(b => builder.Append(b));
                        Trace.WriteLine($"⬇ {DateTime.Now} {builder}");
#endif
                        _io.InvokeBytesReceived(binaryResult.Skip(1).ToArray());
                    }
                }
            }
            finally
            {
                // _ws.Dispose();
            }
        }
예제 #10
0
파일: Program.cs 프로젝트: hpatel98/SCAMP
        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);
            }
        }
예제 #11
0
 private static async Task Receive(ClientWebSocket webSocket)
 {
     byte[] buffer = new byte[receiveChunkSize];
     while (webSocket.State == WebSocketState.Open)
     {                
         var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
         if (result.MessageType == WebSocketMessageType.Close)
         {
             await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
         }
         else
         {
             LogStatus(true, buffer, result.Count);
         }
     }
 }
예제 #12
0
파일: Wamp.cs 프로젝트: MatchWorkshop/No_18
    private async System.Threading.Tasks.Task <Response> ReceiveMessage()
    {
        // Receive one web socket message
        System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> > segments = new System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> >();

        try
        {
            while (true)
            {
                byte[] buffer  = new byte[4096];
                var    segment = new System.ArraySegment <byte>(buffer, 0, buffer.Length);
                System.Net.WebSockets.WebSocketReceiveResult rcvResult = await ws.ReceiveAsync(segment, stopServerTokenSource.Token);

                // Accumulate the byte arrays in a list, we will join them later
                segments.Add(segment.Skip(segment.Offset).Take(rcvResult.Count));

                if (rcvResult.EndOfMessage)
                {
                    break;
                }
            }
        }
        catch (System.Net.WebSockets.WebSocketException e)
        {
            throw e.InnerException;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error receiving response from server.");
        }

        try
        {
            byte[] bytes = segments.SelectMany(t => t).ToArray <byte>();
            string msg   = System.Text.Encoding.UTF8.GetString(bytes);
            return(Parse(msg));
        }
        catch (ErrorException e)
        {
            // Dispatch already built error
            throw e;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error while parsing response from server.");
        }
    }
예제 #13
0
        private async Task ReadEventsAsync()
        {
            var socket = new ClientWebSocket();
            await socket.ConnectAsync(new Uri("ws://localhost:7070/events"), CancellationToken.None);

            while (true)
            {
                var buffer = new byte[1024];
                var segment = new ArraySegment<byte>(buffer);

                var result = await socket.ReceiveAsync(segment, CancellationToken.None);

                var data = Encoding.UTF8.GetString(segment.Array, 0, result.Count);

                Debug.WriteLine(data);
            }
        }
        private async Task ListenAsync()
        {
            var buffer = new byte[ReceiveChunkSize];

            while (_ws.State == WebSocketState.Open && !_wsWorkTokenSource.IsCancellationRequested)
            {
                var stringResult = new StringBuilder();
                var binaryResult = new List <byte>();
                WebSocketReceiveResult result;
                do
                {
                    result = await _ws.ReceiveAsync(new ArraySegment <byte>(buffer), _wsWorkTokenSource.Token);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        Close("io server disconnect");
                    }
                    else if (result.MessageType == WebSocketMessageType.Text)
                    {
                        string str = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        stringResult.Append(str);
                    }
                    else if (result.MessageType == WebSocketMessageType.Binary)
                    {
                        binaryResult.AddRange(buffer.Take(result.Count));
                    }
                } while (!result.EndOfMessage);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string message = stringResult.ToString();
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} {message}");
#endif
                    _parser.Unpack(message);
                }
                else if (result.MessageType == WebSocketMessageType.Binary)
                {
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} Binary message");
#endif
                    _io.InvokeBytesReceived(binaryResult.Skip(1).ToArray());
                }
            }
        }
        // Define other methods and classes here
        private async Task Receive(ClientWebSocket webSocket)
        {
            var buffer = new byte[64];
            while (webSocket.State == WebSocketState.Open)
            {
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else
                {
                    DeserializeAndEnqueue(buffer, result.Count);
                }

                //if(Console.KeyAvailable)
                //    break;
            }
        }
 private static void ReceiveWebsocketMessageAndAppend(ClientWebSocket client, List<String> messages)
 {
     var receiveBuffer = new byte[1024];
     var receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
     try
     {
         var result = client.ReceiveAsync(receiveBufferSegment, CancellationToken.None).Result;
         if (result.Count > 0)
         {
             var message = Encoding.Default.GetString(receiveBuffer.Take(result.Count).ToArray());
             if (message.Contains("error"))
             {
                 throw new Exception("websocket returned an error message");
             }
             messages.Add(message);
         }
     }
     catch (Exception) { }
 }
예제 #17
0
        public async Task EndToEnd_ConnectAndClose_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                var accept = (WebSocketAccept)env["websocket.Accept"];
                Assert.NotNull(accept);

                accept(
                    null,
                    async wsEnv =>
                    {
                        var sendAsync1 = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
                        var receiveAsync1 = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
                        var closeAsync1 = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");

                        var buffer1 = new ArraySegment<byte>(new byte[10]);
                        await receiveAsync1(buffer1, CancellationToken.None);
                        await closeAsync1((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);

                    await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                    WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), CancellationToken.None);

                    Assert.Equal(WebSocketCloseStatus.NormalClosure, readResult.CloseStatus);
                    Assert.Equal("Closing", readResult.CloseStatusDescription);
                    Assert.Equal(0, readResult.Count);
                    Assert.True(readResult.EndOfMessage);
                    Assert.Equal(WebSocketMessageType.Close, readResult.MessageType);
                }
            }
        }
예제 #18
0
        private async Task Receive(ClientWebSocket socket)
        {
            var buffer = new byte[2048];
            while (socket.State == WebSocketState.Open)
            {
                var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else
                {
                    var json = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
                    var notification = JsonConvert.DeserializeObject<WebSocketClientNotification>(json);

                    NotificationReceived?.Invoke(this, new WebSocketClientNotificationEventArgs(notification));

                    Array.Clear(buffer,0,buffer.Length);
                }
            }
        }
예제 #19
0
        public async Task Subscribe(CancellationToken cancel)
        {
            byte[] buffer = new byte[1024 * 1024];
            ArraySegment<byte> segment = new ArraySegment<byte>(buffer);

            ByteString currentRecord = await this.store.GetLastTransaction();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    ClientWebSocket socket = new ClientWebSocket();

                    this.endpoint.Query = string.Format("from={0}", currentRecord.ToString());

                    logger.LogInformation("Connecting to {0}", this.endpoint.Uri);

                    await socket.ConnectAsync(this.endpoint.Uri, cancel);

                    while (true)
                    {
                        WebSocketReceiveResult result = await socket.ReceiveAsync(segment, cancel);
                        if (result.MessageType == WebSocketMessageType.Close)
                            break;

                        ByteString record = new ByteString(buffer.Take(result.Count));
                        await store.AddTransactions(new[] { record });

                        currentRecord = new ByteString(MessageSerializer.ComputeHash(record.ToByteArray()));
                    }
                }
                catch (Exception exception)
                {
                    logger.LogError("Error in the stream subscriber: {0}", exception.ToString());
                }

                await Task.Delay(TimeSpan.FromMinutes(1));
            }
        }
예제 #20
0
파일: SlackAdapter.cs 프로젝트: gep13/nubot
        public override async Task RunAsync(CancellationToken cancellationToken)
        {
            using (var ws = new ClientWebSocket())
            {
                await ws.ConnectAsync(_rtm.WebSocketUri, cancellationToken);

                while (!cancellationToken.IsCancellationRequested)
                {
                    using (var ms = new MemoryStream())
                    {
                        WebSocketReceiveResult result;

                        do
                        {
                            result = await ws.ReceiveAsync(_buffer, cancellationToken);
                            await ms.WriteAsync(_buffer.Array, _buffer.Offset, result.Count, cancellationToken);
                        } while (!result.EndOfMessage);

                        ms.Seek(0, SeekOrigin.Begin);
                        HandleEvent(ms);
                    }
                }
            }
        }
예제 #21
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));
                }
            }
        }
예제 #22
0
        public async Task SubProtocol_SelectLastSubProtocol_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                var accept = (WebSocketAccept)env["websocket.Accept"];
                Assert.NotNull(accept);

                var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
                var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");

                // Select the last sub-protocol from the client.
                string subProtocol = requestHeaders["Sec-WebSocket-Protocol"].Last().Split(',').Last().Trim();

                responseHeaders["Sec-WebSocket-Protocol"] = new string[] { subProtocol + "A" };

                accept(
                    new Dictionary<string, object>() { { "websocket.SubProtocol", subProtocol } },
                    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);
                        // Assume close received
                        await closeAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    });

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

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    client.Options.AddSubProtocol("protocol1");
                    client.Options.AddSubProtocol("protocol2");

                    await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);

                    await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    var receiveBody = new byte[100];
                    WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
                    Assert.Equal(WebSocketMessageType.Close, readResult.MessageType);
                    Assert.Equal("protocol2", client.SubProtocol);
                }
            }
        }
예제 #23
0
        public async Task Receive(ClientWebSocket webSocket)
        {
            byte[] buffer = new byte[1024];
            string TempString = "";
            while (webSocket.State == WebSocketState.Open)
            {
                
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                }
                else
                {
                    TempString = Encoding.UTF8.GetString(buffer);
                    TempString = TempString.Remove(result.Count);
                    if (TempString.Substring(TempString.Length - 1, 1) == "}" || TempString == "hello")
                    {
                        DecodeServerPacket(TempString);
                        TempString = "";
                    }
 
                }
                
                
            }
        }
예제 #24
0
        private async Task ListenAsync()
        {
            while (true)
            {
                var buffer = new byte[ReceiveChunkSize];
                int count  = 0;
                WebSocketReceiveResult result = null;
                while (_ws.State == WebSocketState.Open)
                {
                    try
                    {
                        //result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _wsWorkTokenSource.Token);
                        var subBuffer = new byte[ReceiveChunkSize];
                        result = await _ws.ReceiveAsync(new ArraySegment <byte>(subBuffer), CancellationToken.None);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Close("io server disconnect");
                            break;
                        }
                        else if (result.MessageType == WebSocketMessageType.Text || result.MessageType == WebSocketMessageType.Binary)
                        {
                            if (buffer.Length - count < result.Count)
                            {
                                Array.Resize(ref buffer, buffer.Length + result.Count);
                            }
                            Buffer.BlockCopy(subBuffer, 0, buffer, count, result.Count);
                            count += result.Count;
                        }
                        if (result.EndOfMessage)
                        {
                            break;
                        }
                    }
                    catch (WebSocketException e)
                    {
                        Close(e.Message);
                        break;
                    }
                }
                if (result == null)
                {
                    break;
                }
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string message = Encoding.UTF8.GetString(buffer, 0, count);
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} {message}");
#endif
                    _parser.Unpack(message);
                }
                else if (result.MessageType == WebSocketMessageType.Binary)
                {
#if DEBUG
                    Trace.WriteLine($"⬇ {DateTime.Now} Binary message");
#endif
                    byte[] bytes;
                    if (_io.Options.EIO == 3)
                    {
                        count -= 1;
                        bytes  = new byte[count];
                        Buffer.BlockCopy(buffer, 1, bytes, 0, count);
                    }
                    else
                    {
                        bytes = new byte[count];
                        Buffer.BlockCopy(buffer, 0, bytes, 0, count);
                    }
                    _io.InvokeBytesReceived(bytes);
                }
            }
        }
예제 #25
0
 public Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken)
 {
     return(webSocket.ReceiveAsync(buffer, cancellationToken));
 }
예제 #26
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();
        }
        private async Task<string> ReceiveFromSocket(ClientWebSocket theSocket)
        {

            // receive 
            
            var arraySegment = new ArraySegment<byte>(new Byte[1024 * 256]);
            var res = await theSocket.ReceiveAsync(arraySegment, CancellationToken.None);

            return Encoding.UTF8.GetString(arraySegment.Actualize(res.Count));
        }
        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);
                }
            }
        }
        public async Task Subscribe(CancellationToken cancel)
        {
            byte[] buffer = new byte[1024 * 1024];
            ArraySegment<byte> segment = new ArraySegment<byte>(buffer);

            IServiceScopeFactory scopeFactory = services.GetService<IServiceScopeFactory>();
            ILogger logger = services.GetRequiredService<ILogger>();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    using (IServiceScope scope = scopeFactory.CreateScope())
                    {
                        IStorageEngine storageEngine = scope.ServiceProvider.GetRequiredService<IStorageEngine>();
                        await storageEngine.Initialize();

                        ByteString currentRecord = await storageEngine.GetLastTransaction();

                        ClientWebSocket socket = new ClientWebSocket();

                        this.endpoint.Query = string.Format("from={0}", currentRecord.ToString());

                        logger.LogInformation("Connecting to {0}", this.endpoint.Uri);

                        await socket.ConnectAsync(this.endpoint.Uri, cancel);

                        while (true)
                        {
                            ByteString transaction;

                            using (MemoryStream stream = new MemoryStream(1024))
                            {
                                WebSocketReceiveResult result;

                                do
                                {
                                    result = await socket.ReceiveAsync(segment, cancel);
                                    if (result.MessageType == WebSocketMessageType.Close)
                                        break;

                                    stream.Write(segment.Array, segment.Offset, result.Count);

                                } while (!result.EndOfMessage);

                                stream.Seek(0, SeekOrigin.Begin);

                                using (BinaryReader reader = new BinaryReader(stream))
                                {
                                    transaction = new ByteString(reader.ReadBytes((int)stream.Length));
                                }
                            }

                            await storageEngine.AddTransactions(new[] { transaction });

                            currentRecord = new ByteString(MessageSerializer.ComputeHash(transaction.ToByteArray()));
                        }
                    }
                }
                catch (Exception exception)
                {
                    logger.LogError("Error in the stream subscriber: {0}", exception.ToString());
                }

                await Task.Delay(TimeSpan.FromMinutes(1));
            }
        }
예제 #30
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();
            }
        }
예제 #31
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]);
        }
예제 #32
0
        private async Task ListenAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                var buffer = new byte[ReceiveChunkSize];
                int count  = 0;
                WebSocketReceiveResult result = null;
                while (_ws.State == WebSocketState.Open)
                {
                    try
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }
                        var subBuffer = new byte[ReceiveChunkSize];
                        result = await _ws.ReceiveAsync(new ArraySegment <byte>(subBuffer), cancellationToken);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            OnClosed("io server disconnect");
                            break;
                        }
                        else if (result.MessageType == WebSocketMessageType.Text || result.MessageType == WebSocketMessageType.Binary)
                        {
                            if (buffer.Length - count < result.Count)
                            {
                                Array.Resize(ref buffer, buffer.Length + result.Count);
                            }
                            Buffer.BlockCopy(subBuffer, 0, buffer, count, result.Count);
                            count += result.Count;
                        }
                        if (result.EndOfMessage)
                        {
                            break;
                        }
                    }
                    catch (WebSocketException e)
                    {
                        OnClosed(e.Message);
                        break;
                    }
                }
                if (result == null)
                {
                    break;
                }
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string message = Encoding.UTF8.GetString(buffer, 0, count);
#if DEBUG
                    System.Diagnostics.Trace.WriteLine($"⬇ {DateTime.Now} {message}");
#endif
                    if (OnTextReceived is null)
                    {
                        throw new ArgumentNullException(nameof(OnTextReceived));
                    }
                    OnTextReceived(message);
                }
                else if (result.MessageType == WebSocketMessageType.Binary)
                {
#if DEBUG
                    System.Diagnostics.Trace.WriteLine($"⬇ {DateTime.Now} Binary message");
#endif
                    if (OnTextReceived is null)
                    {
                        throw new ArgumentNullException(nameof(OnTextReceived));
                    }
                    byte[] bytes = new byte[count];
                    Buffer.BlockCopy(buffer, 0, bytes, 0, count);
                    OnBinaryReceived(bytes);
                    //byte[] bytes;
                    //if (_io.Options.EIO == 3)
                    //{
                    //    count -= 1;
                    //    bytes = new byte[count];
                    //    Buffer.BlockCopy(buffer, 1, bytes, 0, count);
                    //}
                    //else
                    //{
                    //    bytes = new byte[count];
                    //    Buffer.BlockCopy(buffer, 0, bytes, 0, count);
                    //}
                    //_io.InvokeBytesReceived(bytes);
                }
            }
        }
예제 #33
0
        private void dispatch()
        {
            const Int32 bufferSize = 128 * 1024;

            byte[] buffer   = new byte[bufferSize];
            bool   breakOut = false;

            try
            {
                while (Interlocked.Read(ref state) != CLOSED)
                {
                    ArraySegment <byte> segment = new ArraySegment <byte>(buffer);

                    System.Net.WebSockets.WebSocketReceiveResult result;
                    System.Threading.Tasks.Task <System.Net.WebSockets.WebSocketReceiveResult> r;

                    try
                    {
                        r = clientWebSocket.ReceiveAsync(segment, System.Threading.CancellationToken.None);
                        r.Wait(CancellationToken.None);
                        result = r.Result;

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Task t1 = clientWebSocket.CloseAsync((System.Net.WebSockets.WebSocketCloseStatus)result.CloseStatus, result.CloseStatusDescription, CancellationToken.None);
                            t1.Wait(CancellationToken.None);

                            notifyClose((int)result.CloseStatus, result.CloseStatusDescription);
                            breakOut = true;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        notifyError(e);
                        break;
                    }

                    int count = result.Count;
                    while (!result.EndOfMessage)
                    {
                        if (count > buffer.Length)
                        {
                            Task t1 = clientWebSocket.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "payload too long", CancellationToken.None);
                            t1.Wait(CancellationToken.None);
                            notifyClose((int)WebSocketCloseStatus.InvalidPayloadData, "payload too long");
                            return;
                        }

                        segment = new ArraySegment <byte>(buffer, count, buffer.Length - count);

                        r = clientWebSocket.ReceiveAsync(segment, CancellationToken.None);
                        r.Wait(CancellationToken.None);
                        result = r.Result;

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            Task t1 = clientWebSocket.CloseAsync((System.Net.WebSockets.WebSocketCloseStatus)result.CloseStatus, result.CloseStatusDescription, CancellationToken.None);
                            t1.Wait(CancellationToken.None);

                            notifyClose((int)result.CloseStatus, result.CloseStatusDescription);
                            breakOut = true;
                            break;
                        }
                        else if (result.Count == 0)
                        {
                            // filled the buffer, resize it
                            var newBuffer = new byte[buffer.Length + bufferSize];
                            Array.Copy(buffer, newBuffer, buffer.Length);
                            buffer = newBuffer;
                        }
                        if (breakOut)
                        {
                            break;
                        }

                        count += result.Count;
                    }

                    // now invoke the callback.
                    if (count > 0)
                    {
                        notifyMessage(buffer, count);
                    }
                }
            }
            catch (Exception) { return; }

            return;
        }
예제 #34
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);
     }            
 }
예제 #35
-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
        }
예제 #36
-1
        private async Task ReceiveMessages(ClientWebSocket socket,string msg, int total)
        {
            var maxMessageSize = 1024;
            var receiveBuffer = new byte[maxMessageSize];

            for (var i = 0; i < 10; i++)
            {
                var ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);

                if (ret.MessageType != WebSocketMessageType.Text) continue;

                var count = ret.Count;
                while (!ret.EndOfMessage)
                {
                    ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
                    count += ret.Count;
                }

                var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);
                Trace.WriteLine(receivedString);
                Interlocked.Increment(ref _counter);
            }
        }