Is there a WebSocket client implemented for .NET? [closed]
Asked Answered
C

11

54

I would like to use WebSockets in my Windows Forms or WPF-application. Is there a .NET-control that is supporting WebSockets implemented yet? Or is there any open source project started about it?

An open source solution for a Java Client supporting WebSockets could also help me.

Charlsiecharlton answered 14/1, 2010 at 14:15 Comment(0)
E
22

Now, SuperWebSocket also includes a WebSocket client implementation SuperWebSocket Project Homepage

Other .NET client implementations include:

Eradis answered 10/3, 2011 at 8:25 Comment(5)
I can't see to see anything in SuperWebSocket about a client implementation? Is it still there?Tallou
In SourceCode/mainline/ClientEradis
The client in SuperWebSocket has been separated into WebSocket4Net: websocket4net.codeplex.comEradis
When I try to connect to socket.io from .NET using WebSocket4Net I see "debug - destroying non-socket.io upgrade". What am I missing?Cadent
WebSocket4Net in github: github.com/kerryjiang/WebSocket4NetEradis
N
24

Here's a quick first pass at porting that Java code to C#. Doesn't support SSL mode and has only been very lightly tested, but it's a start.

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);
    }
}
Nathalia answered 6/4, 2010 at 18:33 Comment(2)
Note that StringBuilder.Append(byte) doesn't do what you think it does -- it appends the textual representation of the byte to the buffer. Building a list of bytes and then converting that byte[] to a string using Encoding.UTF8.GetString(bytes) works better.Till
+1 worked for me. I ended up modifying mStream = new SslStream(mClient.GetStream()); and adding mStream.AuthenicateAsClient(host);, and that was all that was needed for SSL support.Leonidaleonidas
E
22

Now, SuperWebSocket also includes a WebSocket client implementation SuperWebSocket Project Homepage

Other .NET client implementations include:

Eradis answered 10/3, 2011 at 8:25 Comment(5)
I can't see to see anything in SuperWebSocket about a client implementation? Is it still there?Tallou
In SourceCode/mainline/ClientEradis
The client in SuperWebSocket has been separated into WebSocket4Net: websocket4net.codeplex.comEradis
When I try to connect to socket.io from .NET using WebSocket4Net I see "debug - destroying non-socket.io upgrade". What am I missing?Cadent
WebSocket4Net in github: github.com/kerryjiang/WebSocket4NetEradis
M
12

Support for WebSockets is coming in .NET 4.5. That links also contains an example using the System.Net.WebSockets.WebSocket class.

Mellar answered 23/7, 2012 at 20:15 Comment(1)
From the docs "the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012" - ie. it wont work with older versions of windows.Barone
H
7

Kaazing.com provide a .NET client library that can access websockets. They have tutorials online at Checklist: Build Microsoft .NET JMS Clients and Checklist: Build Microsoft .NET AMQP Clients

There is a Java Websocket Client project on github.

Humanitarian answered 14/1, 2010 at 14:40 Comment(0)
E
5

There is a client implementation: https://github.com/kerryjiang/WebSocket4Net!

Eradis answered 9/1, 2012 at 2:32 Comment(0)
S
4

another choice: XSockets.Net, has implement server and client.

can install server by:

PM> Install-Package XSockets

or install client by:

PM> Install-Package XSockets.Client

current version is: 3.0.4

Seward answered 15/2, 2014 at 3:29 Comment(0)
N
3

Here is the list of .net supported websocket nuget packages

Websocket pakages.

I prefer following clients

  1. Alchemy websocket
  2. SocketIO
Nika answered 17/5, 2013 at 18:30 Comment(0)
L
1

it's a pretty simple protocol. there's a java implementation here that shouldn't be too difficult to translate into c#. if i get around to doing it, i'll post it up here...

Livingstone answered 25/2, 2010 at 5:36 Comment(0)
S
1

Recently the Interoperability Bridges and Labs Center released a prototype implementation (in managed code) of two drafts of the WebSockets protocol specification:

draft-hixie-thewebsocketprotocol-75 and draft-hixie-thewebsocketprotocol-76

The prototype can be found at HTML5 Labs. I put in this blog post all the information I found (until now) and snippets of code about how this can be done using WCF.

Sochor answered 25/12, 2010 at 19:41 Comment(0)
W
1

If you'd like something a little more lightweight, check out a C# server that a friend and I released: https://github.com/Olivine-Labs/Alchemy-Websockets

Supports vanilla websockets as well as flash websockets. It was built for our online game with a focus on scalability and efficiency.

Wendolynwendt answered 24/3, 2011 at 20:24 Comment(0)
U
0

There is also Alchemy. http://olivinelabs.com/Alchemy-Websockets/ which is rather cool.

Unfounded answered 11/10, 2012 at 23:13 Comment(3)
and which is not a WebSocket clientOrthotropous
Yes it is. There is a WebSocket client lib with it. Look again!Unfounded
I don't see it as a lib actually. There is a WebSocketClient class though, rightOrthotropous

© 2022 - 2024 — McMap. All rights reserved.