mozilla

Revision 352737 of Writing a WebSocket server in C#

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

Revision Content

Introduction

If you want 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 of it looks like this:

TcpListener(IPAddress localaddr, int port)

Revision Source

<h2 id="Introduction">Introduction</h2>
<p>If you want 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 of it looks like this:</p>
<pre>
TcpListener(IPAddress localaddr, int port)</pre>
Revert to this revision