将 c# ClientWebSocket 与流一起使用 [英] Using c# ClientWebSocket with streams

查看:107
本文介绍了将 c# ClientWebSocket 与流一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究使用 websockets 在客户端/代理和服务器之间进行通信,并决定为此目的研究 C#.虽然我之前使用过 Websockets 和 C#,但这是我第一次同时使用两者.第一次尝试使用以下指南:http://www.codeproject.com/Articles/618032/Using-WebSocket-in-网络部分

I am currently looking into using websockets to communicate between a client/agent and a server, and decided to look at C# for this purpose. Although I have worked with Websockets before and C# before, this is the first time I using both together. The first attempt used the following guide: http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-Part

public static void Main(string[] args)
{
    Task t = Echo();
    t.Wait();
}

private static async Task Echo()
{
    using (ClientWebSocket ws = new ClientWebSocket())
    {
        Uri serverUri = new Uri("ws://localhost:49889/");
        await ws.ConnectAsync(serverUri, CancellationToken.None);
        while (ws.State == WebSocketState.Open)
        {
            Console.Write("Input message ('exit' to exit): ");
            string msg = Console.ReadLine();
            if (msg == "exit")
            {
                break;
            }
            ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
            await ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
            ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]);
            WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
            Console.WriteLine(Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count));
        }
    }
}

虽然这似乎按预期工作,但我想知道是否有任何方法可以将 .NET 中的内置流/读取器与 ClientWebSocket 一起使用?

Although this seems to work as expected, I was wondering if there is any way I can use the built in streams/readers in .NET with ClientWebSocket?

我觉得奇怪的是,Microsoft 拥有一套丰富且完善的流和读取器类,但随后决定实现 ClientWebSocket,使其仅具有读取必须手动处理的字节块的能力.

Seems odd to me that Microsoft has this rich well established set of stream and reader classes, but then decides to implement ClientWebSocket with only the ability to read blocks of bytes that must be handled manually.

假设我想传输 xml,将套接字流包装在 XmlTextReader 中对我来说很容易,但这对于 ClientWebSocket 来说并不明显.

Lets say I wanted to transfer xml, it would be easy for me to just wrap the socket stream in a XmlTextReader, but this is not obvious with ClientWebSocket.

推荐答案

为什么不使用字节数组?如何使用 XmlDictionaryReader.CreateTextReader 接受来自系统的字节数组.Runtime.Serialization 程序集?.工作代码:

Why don't work with byte arary? What about using XmlDictionaryReader.CreateTextReader which accept byte array from System.Runtime.Serialization assembly?. Working code:

namespace XmlReaderOnByteArray
{
    using System;
    using System.Xml;

    class Program
    {
        public static void Main(string[] args)
        {
            // Some XML
            string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                <note>
                <to>Tove</to>
                <from>Jani</from>
                <heading>Reminder</heading>
                <body>Don't forget me this weekend!</body>
                </note>";
            // Get buffer from string
            ArraySegment<byte> arraySegment = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(xml));
            // Use XmlDictionaryReader.CreateTextReader to create reader on byte array
            using (var reader = XmlDictionaryReader.CreateTextReader(arraySegment.Array, new XmlDictionaryReaderQuotas())) {
                while (reader.Read()) {
                    Console.WriteLine("{0}[{1}] => {2}", reader.Name, reader.NodeType, reader.Value);
                }
            }
        }
    }
}

这篇关于将 c# ClientWebSocket 与流一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆