54

Windows フォームまたは WPF アプリケーションで WebSocket を使用したいと考えています。まだ実装されている WebSockets をサポートしている .NET コントロールはありますか? それとも、それについて開始されたオープンソース プロジェクトはありますか?

WebSocket をサポートする Java クライアントのオープン ソース ソリューションも役に立ちます。

4

11 に答える 11

24

以下は、その 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<string, string> 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<string, string> 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<string, string> 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);
    }
}
于 2010-04-06T18:33:12.613 に答える
22

現在、SuperWebSocket には WebSocket クライアントの実装も含まれています。 SuperWebSocket プロジェクトのホームページ

その他の .NET クライアントの実装には、次のものがあります。

于 2011-03-10T08:25:27.907 に答える
11

.NET 4.5 では、WebSocket のサポートが予定されています。そのリンクには、 System.Net.WebSockets.WebSocketクラスを使用した例も含まれています。

于 2012-07-23T20:15:28.347 に答える
7

Kaazing.com は、WebSocket にアクセスできる .NET クライアント ライブラリを提供します。Checklist: Build Microsoft .NET JMS ClientsおよびChecklist: Build Microsoft .NET AMQP Clientsにオンライン チュートリアルがあります。

github にJava Websocket クライアントプロジェクトがあります。

于 2010-01-14T14:40:45.343 に答える
5

クライアント実装があります: http://websocket4net.codeplex.com/ !

于 2012-01-09T02:32:54.990 に答える
1

もう少し軽量なものが必要な場合は、友人と私がリリースしたC#サーバーをチェックしてください:https ://github.com/Olivine-Labs/Alchemy-Websockets

バニラWebSocketとフラッシュWebSocketをサポートします。これは、スケーラビリティと効率に重点を置いたオンラインゲーム用に構築されました。

于 2011-03-24T20:24:40.703 に答える
1

これは非常に単純なプロトコルです。ここには、c#に変換するのがそれほど難しくないはずのJava実装があります。うまくいったら、ここに投稿します...

于 2010-02-25T05:36:53.073 に答える
1

最近、Interoperability Bridges and Labs Center は、WebSockets プロトコル仕様の 2 つのドラフトの (マネージド コードでの) プロトタイプ実装をリリースしました。

draft-hixie-thewebsocketprotocol-75およびdraft-hixie-thewebsocketprotocol-76

プロトタイプは HTML5 Labs にあります。このブログ投稿には、(これまでに) 見つけたすべての情報と、WCF を使用してこれを行う方法に関するコードのスニペットを掲載しました。

于 2010-12-25T19:41:51.950 に答える
0

錬金術もあります。http://olivinelabs.com/Alchemy-Websockets/はかなりクールです。

于 2012-10-11T23:13:28.203 に答える