当前位置:  开发笔记 > 编程语言 > 正文

是否为.NET实现了WebSocket客户端?

如何解决《是否为.NET实现了WebSocket客户端?》经验,为你挑选了5个好方法。

我想在我的Windows窗体或WPF应用程序中使用WebSockets.是否有支持WebSockets实现的.NET控件?或者是否有任何开源项目开始呢?

支持WebSockets的Java客户端的开源解决方案也可以帮助我.



1> jhurliman..:

这是将Java代码移植到C#的快速第一步.不支持SSL模式,只进行了非常轻微的测试,但这是一个开始.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class WebSocket
{
    private Uri mUrl;
    private TcpClient mClient;
    private NetworkStream mStream;
    private bool mHandshakeComplete;
    private Dictionary mHeaders;

    public WebSocket(Uri url)
    {
        mUrl = url;

        string protocol = mUrl.Scheme;
        if (!protocol.Equals("ws") && !protocol.Equals("wss"))
            throw new ArgumentException("Unsupported protocol: " + protocol);
    }

    public void SetHeaders(Dictionary headers)
    {
        mHeaders = headers;
    }

    public void Connect()
    {
        string host = mUrl.DnsSafeHost;
        string path = mUrl.PathAndQuery;
        string origin = "http://" + host;

        mClient = CreateSocket(mUrl);
        mStream = mClient.GetStream();

        int port = ((IPEndPoint)mClient.Client.RemoteEndPoint).Port;
        if (port != 80)
            host = host + ":" + port;

        StringBuilder extraHeaders = new StringBuilder();
        if (mHeaders != null)
        {
            foreach (KeyValuePair header in mHeaders)
                extraHeaders.Append(header.Key + ": " + header.Value + "\r\n");
        }

        string request = "GET " + path + " HTTP/1.1\r\n" +
                         "Upgrade: WebSocket\r\n" +
                         "Connection: Upgrade\r\n" +
                         "Host: " + host + "\r\n" +
                         "Origin: " + origin + "\r\n" +
                         extraHeaders.ToString() + "\r\n";
        byte[] sendBuffer = Encoding.UTF8.GetBytes(request);

        mStream.Write(sendBuffer, 0, sendBuffer.Length);

        StreamReader reader = new StreamReader(mStream);
        {
            string header = reader.ReadLine();
            if (!header.Equals("HTTP/1.1 101 Web Socket Protocol Handshake"))
                throw new IOException("Invalid handshake response");

            header = reader.ReadLine();
            if (!header.Equals("Upgrade: WebSocket"))
                throw new IOException("Invalid handshake response");

            header = reader.ReadLine();
            if (!header.Equals("Connection: Upgrade"))
                throw new IOException("Invalid handshake response");
        }

        mHandshakeComplete = true;
    }

    public void Send(string str)
    {
        if (!mHandshakeComplete)
            throw new InvalidOperationException("Handshake not complete");

        byte[] sendBuffer = Encoding.UTF8.GetBytes(str);

        mStream.WriteByte(0x00);
        mStream.Write(sendBuffer, 0, sendBuffer.Length);
        mStream.WriteByte(0xff);
        mStream.Flush();
    }

    public string Recv()
    {
        if (!mHandshakeComplete)
            throw new InvalidOperationException("Handshake not complete");

        StringBuilder recvBuffer = new StringBuilder();

        BinaryReader reader = new BinaryReader(mStream);
        byte b = reader.ReadByte();
        if ((b & 0x80) == 0x80)
        {
            // Skip data frame
            int len = 0;
            do
            {
                b = (byte)(reader.ReadByte() & 0x7f);
                len += b * 128;
            } while ((b & 0x80) != 0x80);

            for (int i = 0; i < len; i++)
                reader.ReadByte();
        }

        while (true)
        {
            b = reader.ReadByte();
            if (b == 0xff)
                break;

            recvBuffer.Append(b);           
        }

        return recvBuffer.ToString();
    }

    public void Close()
    {
        mStream.Dispose();
        mClient.Close();
        mStream = null;
        mClient = null;
    }

    private static TcpClient CreateSocket(Uri url)
    {
        string scheme = url.Scheme;
        string host = url.DnsSafeHost;

        int port = url.Port;
        if (port <= 0)
        {
            if (scheme.Equals("wss"))
                port = 443;
            else if (scheme.Equals("ws"))
                port = 80;
            else
                throw new ArgumentException("Unsupported scheme");
        }

        if (scheme.Equals("wss"))
            throw new NotImplementedException("SSL support not implemented yet");
        else
            return new TcpClient(host, port);
    }
}


请注意,StringBuilder.Append(byte)不会按照您的想法执行操作 - 它会将字节的文本表示形式附加到缓冲区.构建一个字节列表,然后使用Encoding.UTF8.GetString(bytes)将该byte []转换为字符串效果更好.

2> Kerry Jiang..:

现在,SuperWebSocket还包括一个WebSocket客户端实现 SuperWebSocket Project主页

其他.NET客户端实现包括:

Microsoft WebSocket客户端原型

WebSocket的夏普

安达


SuperWebSocket中的客户端已分为WebSocket4Net:http://websocket4net.codeplex.com/

3> Stephen Rudo..:

.NET 4.5支持WebSockets .该链接还包含使用System.Net.WebSockets.WebSocket类的示例.


从文档"Windows 8和Windows Server 2012支持客户端和服务器WebSockets的唯一公共实现" - 即.它不适用于旧版本的Windows.

4> Robert Chris..:

Kaazing.com提供了一个可以访问websockets的.NET客户端库.他们在Checklist上有在线教程:构建Microsoft .NET JMS客户端和清单:构建Microsoft .NET AMQP客户端

github上有一个Java Websocket Client项目.



5> Kerry Jiang..:

有一个客户端实现:http://websocket4net.codeplex.com/!

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有