Writing a WebSocket server in C#

  • Revision slug: WebSockets/Writing_WebSocket_server
  • Revision title: Writing WebSocket server
  • Revision id: 352765
  • Created:
  • Creator: lumia
  • Is current revision? No
  • Comment

Revision Content

Introduction

If you would like to use the WebSocket API, it is useful if you have a server. :-) In this article I will show you how to write one in C#.

In lots of server side programming language you can do it, but to keep things simple and more understandable, I chose Microsoft's language.

This server gives which is required by RFC 6455 so it will only handle connections from Chrome version 16, Firefox 11, IE 10 and over.

First steps

WebSocket is communicating over a TCP (Transmission Control Protocol) connection, luckily C# has a TcpListener class which name tells everything. It is in System.Net.Sockets namespace.

It is a good idea to use using keyword to write less. It means you have not to retype the name of namespace if you use classes from it.

TcpListener

Constructor:

TcpListener(System.Net.IPAddress localaddr, int port)

You set here, where the server will be reachable.

To easily give the expected type to first parameter use the Parse static method of IPAddress.

Methods:

  • Start()
  • System.Net.Sockets.TcpClient AcceptTcpClient()
    Waiting for a connection and if it is over TCP, accepts it and returns it as a TcpClient object.

Let us use up what we have learnt.

​using System.Net.Sockets;
using System.Net;
using System;

class Server {
    public static void Main() {
        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);

        server.Start();
        Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);

        TcpClient client = server.AcceptTcpClient();

        Console.WriteLine("A client connected.");
    }
}

TcpClient

Methods:

  • System.Net.Sockets.NetworkStream GetStream()
    Gets the stream which is the communication channel. Write- and readable by both sides.

Properties:

  • int Available
    Number of bytes of data has been sent. Value of it is 0 until NetworkStream.DataAvailable is false.

NetworkStream

Methods:

Write(Byte[] buffer, int offset, int size)

Writes bytes from buffer from offset to size to stream.

Read(Byte[] buffer, int offset, int size)

Reads bytes to buffer from offset to size from stream.

Let us extend our example.

TcpClient client = server.AcceptTcpClient();

Console.WriteLine("A client connected.");

NetworkStream stream = client.GetStream();

//enter to an infinite cycle to be able to handle every change in stream
while (true) {
    while (!stream.DataAvailable);

    Byte[] bytes = new Byte[client.Available];

    stream.Read(bytes, 0, bytes.Length);
}

Revision Source

<h2 id="Introduction">Introduction</h2>
<p>If you would like to use the WebSocket API, it is useful if you have a server. :-) In this article I will show you how to write one in C#.</p>
<div class="note">
  <p>In lots of server side programming language you can do it, but to keep things simple and more understandable, I chose Microsoft's language.</p>
</div>
<p>This server gives which is required by <a href="http://tools.ietf.org/html/rfc6455" title="http://tools.ietf.org/html/rfc6455">RFC 6455</a> so it will only handle connections from Chrome version 16, Firefox 11, IE 10 and over.</p>
<h2 id=".C2.A0">First steps</h2>
<p>WebSocket is communicating over a <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" title="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP (Transmission Control Protocol)</a>&nbsp;connection, luckily C# has a <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx">TcpListener</a> class which name tells everything. It is in <em>System.Net.Sockets</em> namespace.</p>
<div class="note">
  <p><span style="line-height: 1.572;">It is a good idea to use </span><em style="line-height: 1.572;"><span style="line-height: 1.572;">u</span><span style="line-height: 1.572;">sing</span></em><span style="line-height: 1.572;"> keyword to write less. It means you have not to retype the name of namespace if you use classes from it.</span></p>
</div>
<h3>TcpListener</h3>
<p>Constructor:</p>
<pre>
TcpListener(System.Net.<a href="http://msdn.microsoft.com/en-us/library/system.net.ipaddress.aspx">IPAddress</a> localaddr, int port)</pre>
<p>You set here, where the server will be reachable.</p>
<div class="note">
  <p><span style="line-height: 1.572;">To easily give the expected type to first parameter use the&nbsp;</span><em style="line-height: 1.572;">Parse</em><span style="line-height: 1.572;">&nbsp;static method of&nbsp;</span><em style="line-height: 1.572;">IPAddress.</em></p>
</div>
<p><span style="line-height: 1.572;">Methods</span><span style="line-height: 1.572;">:</span></p>
<ul>
  <li><span style="line-height: 1.572;">Start()</span></li>
  <li><span style="line-height: 1.572;">System.Net.Sockets.<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx">TcpClient</a> AcceptTcpClient()<br />
    Waiting for a connection and if it is over TCP, accepts it and returns it as a TcpClient object.</span></li>
</ul>
<p><span style="line-height: 1.572;">Let us use up what we have learnt.</span></p>
<pre>
<span style="line-height: 1.572;">​using System.Net.Sockets;
using System.Net;
using System;

class Server {
    public static void Main() {
        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);

        server.Start();
        Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);

        TcpClient client = server.AcceptTcpClient();

        </span><span style="line-height: 1.572;">Console.WriteLine("A client connected.");
</span><span style="line-height: 1.572;">    }
}</span></pre>
<h3><span style="line-height: 1.572;">TcpClient</span></h3>
<p>Methods:</p>
<ul>
  <li>System.Net.Sockets.<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx" title="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx">NetworkStream</a> GetStream()<br />
    Gets the stream which is the communication channel. Write- and readable by both sides.</li>
</ul>
<p>Properties:</p>
<ul>
  <li>int Available<br />
    Number of bytes of data has been sent. Value of it is 0 until <em>NetworkStream.DataAvailable</em> is <em>false</em>.</li>
</ul>
<h3>NetworkStream</h3>
<p>Methods:</p>
<pre>
Write(Byte[] buffer, int offset, int size)</pre>
<p>Writes bytes from <em>buffer</em> from <em>offset</em>&nbsp;to <em>size</em> to stream.</p>
<pre>
<span style="line-height: 1.572;">Read(Byte[] buffer, int offset, int size)</span></pre>
<p>Reads bytes to <em>buffer</em> from <em>offset&nbsp;</em>to <em>size</em> from stream.</p>
<p>Let us extend our example.</p>
<pre>
TcpClient client = server.AcceptTcpClient();

Console.WriteLine("A client connected.");

NetworkStream stream = client.GetStream();

//enter to an infinite cycle to be able to handle every change in stream
while (true) {
    while (!stream.DataAvailable);

    Byte[] bytes = new Byte[client.Available];

    stream.Read(bytes, 0, bytes.Length);
}</pre>
Revert to this revision