Writing a WebSocket server in C#

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#. You can do it in any server-side language, but to keep things simple and more understandable, I chose Microsoft's language.

This server conforms to RFC 6455 , so it will only handle connections from Chrome version 16, Firefox 11, IE 10 and over.

First steps

WebSockets communicate over a TCP (Transmission Control Protocol) connection. Luckily, C# has a TcpListener class which does as the name suggests. It is in the System.Net.Sockets namespace.

Note: It is a good idea to include the namespace with the using keyword in order to write less. It allows usage of a namespace's classes without typing the full namespace every time.