当前位置: 首页>>代码示例>>C#>>正文


C# ClientWebSocket.SendAsync方法代码示例

本文整理汇总了C#中System.Net.WebSockets.ClientWebSocket.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ClientWebSocket.SendAsync方法的具体用法?C# ClientWebSocket.SendAsync怎么用?C# ClientWebSocket.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebSockets.ClientWebSocket的用法示例。


在下文中一共展示了ClientWebSocket.SendAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestWebSockets

        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)}");
        }
开发者ID:leloulight,项目名称:dnx,代码行数:15,代码来源:Program.cs

示例2: TestConnectWebSocket

        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");
        }
开发者ID:ngdadu,项目名称:embedio,代码行数:26,代码来源:WebSocketsModuleTest.cs

示例3: WebsocketBasic

        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));
                    }
                }
            }
        }
开发者ID:Xamarui,项目名称:Katana,代码行数:27,代码来源:WebSocketTest.cs

示例4: RunSample

        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));
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:25,代码来源:Program.cs

示例5: TestMethod1

        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);
        }
开发者ID:jn2304,项目名称:top-push,代码行数:17,代码来源:UnitTest1.cs

示例6: Send

        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);
        }
开发者ID:Indifer,项目名称:Test,代码行数:10,代码来源:Program.cs

示例7: Send

        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);
            }
        }
开发者ID:paulbatum,项目名称:WebSocket-Samples,代码行数:15,代码来源:Client.cs

示例8: Run

        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);
            }
        }
开发者ID:hpatel98,项目名称:SCAMP,代码行数:22,代码来源:Program.cs

示例9: Send

        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);
            }
        }
开发者ID:chaoscode,项目名称:CSharp-RustIO-Client,代码行数:15,代码来源:Form1.cs

示例10: RespondToMicrosoftWebSocketClient

 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);
     }            
 }
开发者ID:ReinhardHsu,项目名称:NetGain,代码行数:14,代码来源:WebSocketsTests.cs

示例11: AuthorizationTest

        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]);
        }
开发者ID:tdupont750,项目名称:Owin.WebSocket,代码行数:69,代码来源:OwinFleckTests.cs

示例12: SendIntegrationTestMessages

        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();
            }
        }
开发者ID:tdupont750,项目名称:Owin.WebSocket,代码行数:35,代码来源:FleckTestsBase.cs

示例13: Subscribe

        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);
                }
            }
        }
开发者ID:destenson,项目名称:CoinbaseExchange.NET,代码行数:65,代码来源:RealtimeOrderBookClient.cs

示例14: EndToEnd_EchoData_Success

        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));
                }
            }
        }
开发者ID:tkggand,项目名称:katana,代码行数:44,代码来源:OwinWebSocketTests.cs

示例15: send

 private static async Task send(ClientWebSocket ws, object message)
 {
     await ws.SendAsync(new ArraySegment<byte>(Serializer.Serialize(message)), WebSocketMessageType.Binary, true, CancellationToken.None);
 }
开发者ID:Shuffle-Game,项目名称:AnyCardGame,代码行数:4,代码来源:Program.cs


注:本文中的System.Net.WebSockets.ClientWebSocket.SendAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。