将c#ClientWebSocket与流一起使用

agn*_*aft 17 c# websocket

我目前正在研究使用websockets在客户端/代理和服务器之间进行通信,并决定为此目的查看C#.虽然之前我曾经使用过Websockets和C#,但这是我第一次使用它们.第一次尝试使用以下指南: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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

对我来说似乎很奇怪,微软拥有这套丰富完善的流和读取器类,但后来决定实现ClientWebSocket只能读取必须手动处理的字节块.

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

Art*_*yan 3

为什么不使用字节数组?使用从 System.Runtime.Serialization 程序集接受字节数组的 XmlDictionaryReader.CreateTextReader怎么样?。工作代码

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)