HTML 5 C# Web Sockets server and ASP.NET client implementation
In the previous post we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.
I’ve developed a very basic Web Socket server implementation in C# just as a proof of concept. It handles the most basic operations you would expect from a server: start a new connection, disconnect, and send and receive data. Besides, I’ve developed the client part as well using regular ASP.NET. Actually it’s just plain HTML and JavaScript being served from an ASP.NET server – this example doesn’t use any fancy runat=server controls or anything of the like. The functionality is achieved with very simple and easy to understand JavaScript.
So what does this example do? It provides two projects: a Web Socket server and a Web Socket client. The server is a windows console application that once executed just sits there waiting for a connection request. When a client connects, the server sends its date and time to the client every 10 seconds. The client is a web page with some controls to connect/disconnect and to send data to the server, as well as a log window to see what’s going on. Take a look at the example at the bottom of the page.
Here’s a description of the public members of the Web Socket Server:
// Possible status of the server
enum ServerStatusLevel { Off, WaitingConnection, ConnectionEstablished };
// Constructor of the server with default values
WebSocketServer();
// Constructor of the server with the specified values
WebSocketServer (int serverPort, string serverLocation, string connectionOrigin);
// Close the server and release all resources
void Dispose();
// Start the server and make it listen for connection requests
void StartServer();
// Send data to the connected client
void Send (string message);
// Whether events should be logged or not
bool LogEvents;
// Origin of the connection
string ConnectionOrigin;
// Location of the server
string ServerLocation;
// Port of the server
int ServerPort;
// Current status of the server
ServerStatusLevel Status;
// Fired when data is received from the client
event DataReceivedEventHandler DataReceived;
// Fired when client is disconnected
event DisconnectedEventHandler Disconnected;
// Fired when a new connection is established
event NewConnectionEventHandler NewConnection;
Note how I provide two constructors for the Web Socket Server class: one with default parameters (if you want to keep it as simple as possible), and another one to specify the values you want. Anyways, you can still change them after creating the new instance, as the properties are public. You can also specify whether you want the server to log out the events to the console with the LogEvents property.
In order to get the data being sent from the client, you must attach your own function to the DataReceived event, which will then receive the message as a parameter.
So here’s how you would use this Web Socket Server:
public void Test()
{
WebSocketServer WSServer = new WebSocketServer(); // Default values
WSServer.NewConnection += new NewConnectionEventHandler(WSServer_NewConnection);
WSServer.Disconnected += new DisconnectedEventHandler(WSServer_Disconnected);
WSServer.DataReceived += new DataReceivedEventHandler(WSServer_DataReceived);
WSServer.StartServer();
}
void WSServer_DataReceived(string message, EventArgs e)
{
Console.WriteLine("Data received from the client: " + message);
}
void WSServer_Disconnected(EventArgs e)
{
Console.WriteLine("Server disconnected");
}
void WSServer_NewConnection(EventArgs e)
{
Console.WriteLine("New connection established");
WSServer.Send("Hello new client! I hope you enjoy your visit!");
}
It’s a very simple Web Socket server, so it’s very easy to use. You shouldn’t have much problem understanding it.
Go ahead and download the Visual Studio solution and give it a try!
UPDATE (October 12th, 2010):
The Web Socket protocol is not closed yet, so it is being constantly updated. This means that previous Web Socket server implementations might stop working after an update has been made to the API. The original version of the code I released here complied with version 75 of the Web Socket draft. The current version is 76, so I updated my code and released a second project.
No idea of what I’m talking about? I’ll make it easy for you… download the v76 implementation first, and if it doesn’t work then check out the v75 implementation. If you’re using one of the latest browsers, you should have no trouble.
WebSocketsTest (draft 75).zip (Older browsers)
WebSocketsTest (draft 76).zip (Latest browsers)


June 24, 2010 - 22:58
Wow, just downloaded your zip file and that’s pretty cool.I just watched Remy Sharp at NDC2010 and got me interested in web sockets. Not sure what I’ll use it for yet, but opens up possibilities.
July 27, 2010 - 22:56
Genial post and this enter helped me alot in my college assignement. Gratefulness you for your information.
July 28, 2010 - 07:58
Beautiful website you have here, very informative post too, thanks
August 5, 2010 - 20:39
What a great resource!
August 14, 2010 - 19:21
Great example. I have one question. I changed the code so the websocket server is started from the web application. This works on my local host. However I want to make it to work on my hosting server. In the example you create new socket object and bind it to some port. But usually ports are blocked by firewalls. Is there any alternative implementation for this?
August 17, 2010 - 11:34
Yeah, that would be a problem. You may need to tweak the configuration of the firewall to allow connections to your port. Check with the hosting company.
August 24, 2010 - 03:21
Great site. A lot of useful information here. I’m sending it to some friends!
September 16, 2010 - 08:15
Hi !
Looks great, but does not work for me.
After some “research”, I found, it may have
worked for the -75 version of the websocket
draft. My browsers use the -76 version and this
project works:
http://nugget.codeplex.com/
br++mabra
September 16, 2010 - 09:04
Yeap, you’re right. I tested the app with Google Chrome 5.0, and it worked perfectly. However it does not work with Chrome 6.0 on my machine. I’ll have to take a look at it.
I’ll publish the new version here ASAP. Thanks for alerting me!
September 16, 2010 - 16:52
I successfully built the demo using MonoDevelop 2.4. I can start the server but when I run the client, every time I click Connect then I get this:
Trying to connect to the server …
Connection closed.
The server console shows this:
New connection from 127.0.0.1:8181 requested. Handshaking …
Reading handshake …
GET /test HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: localhost:8181
Origin: http://127.0.0.1:8080
Sending handshake …
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: http://localhost:8080
WebSocket-Location: ws://localhost:8181/test
Any idea of what’s going on?
September 22, 2010 - 22:07
What browser are you using? Seems the Web Socket protocol implementation changed a bit in Google Chrome 6. I’m taking a look at it as I’m writing this. Works fine with Chrome 5, though
October 7, 2010 - 03:14
any updates on making this work in Chrome 6? looks like a really cool implementation
October 7, 2010 - 21:10
Working on it … I’ll publish the new version here as soon as I get it ready. I’ll have it working in the next few days. Stay tuned!
October 8, 2010 - 11:32
i tried your code n got following error , when i connect from browser,
1: server uses dos prompt
2: Server started . Listening for connection request..
New connection for 127.0.0.1:8282 requested . Handshaking….
Get /Test HTTP/1.1
Upgrade: Websocket
Connection:Upgrade
Host: Localhost:8282
Origin: http://localhost:8181
Ser-WebSocket -Key1: ‘1478 4% 5n 368 8
Sec–WebSocket-Key2: “14F7998c%2Dg6xnD 25
Sending handshake …
HTTP/1.1 101 WEb Socket Protocol Handshake
Upgrade:WebSocket
Connection:Upgrade
WebSocket-Origin: http://localhost:8282
WebSocket -Location :ws://localhost:8282/test
New connection from 172.0.0.1:8282 established.
Data sent to the client [" Time at the Server: 08/10/2010 17:21:21 "]
client Disconnected.
Waiting for another connection attempt…
when i connect with in 2 second cleint Diconnected…
Where the problem is : ?
October 10, 2010 - 19:18
The web socket protocol changed a bit since I wrote this project. I’m working on it. Stay tuned!
October 11, 2010 - 21:50
Hey, Oliver!
Very good WebSocket implementation. I hope you’ll have success solving the challenge of WebSocket draft 76.
I’m trying to solve this problem too, but I’m not having success with the challenge.
October 12, 2010 - 20:16
I have updated the code. The server now follows the Web Socket protocol draft 76. This means that it is now working in the latest web browsers. Should be working fine now in Chrome 6 and 7. I have made available both versions of the project, in case there’s somebody with an older browser.
In case somebody is interested, a new security check has been included in the new protocol draft. We now have to take the keys the client sends, make some processing and return a MD5 hash to the client. In the previous version of my server I was failing to do this, so the client wouldn’t accept my connection request.
Enjoy!
October 15, 2010 - 22:43
Hi, Oliver,
Thank you for the great demo. Have you worked out how to handle multiple clients?
October 16, 2010 - 12:54
Once you get the basic server working, setting it up to handle multiple clients shouldn’t be much more trouble. However, I never intended to do so, as this was only a demonstration to get a feeling of what this hype of web sockets is about.
You can get my code and extend it to fit your needs, though. Or, if there’s many people who actually request it, I could take a look at it myself.
November 2, 2010 - 18:52
Hi Oliver,
Thanks for the code. I just tried the project and it doesn’t work. I’m using latest chrome browser. The error happens trying to send info back to the client:
ConnectionSocket.Send(Encoding.UTF8.GetBytes(message)); line 393 in WebSocketServer.cs
error is: “An established connection was aborted by the software in your host machine”. I did turn off the firewall, so its not that.
Anything you can think of?
November 5, 2010 - 17:23
I can’t reproduce the error. Any other hint you could give me?
November 5, 2010 - 23:13
Thanks for the response Oliver. I dont have much more though. Just going to screw around with my system and the code until I figure out what is failing.
Like I said its failing on ConnectionSockent.Send (…message));, but not on firstByte. Maybe some protocol changed, just have to sit there and figure it out I guess. If I find what it is I’ll post it back here.
November 8, 2010 - 21:34
Yes, if you find what’s going I’d appreciate it if you could post it here, so some other user could benefit from it as well.
Cheers!
November 27, 2010 - 22:34
i’ve tested it in chrome 6, works fine.
December 3, 2010 - 10:46
amazing post about websocket implementation.it’s very grateful sharing.
December 7, 2010 - 23:49
Hey oliver
thanx for the nice post.. but um getting an error when i start the web page and it says
Warning 2 The ‘targetFramework’ attribute is not declared.”
what should i do? i am using visual studio 2008.. should i have to use visual studio 2010?
December 9, 2010 - 21:02
The problem will likely be that this project was designed for ASP.NET 4.0. Since VS 2008 supports up to ASP.NET 3.5, you might be getting this error.
So yes, you have to use Visual Studio 2010. If you don’t have a copy, you can download VS 2010 Express Edition for free from the Microsoft site.
Cheers!
December 23, 2010 - 17:07
Oliver,
This is a pretty cleat implementation of the WebSockets protocol. Would you be so kind to make it multiple sessions?
Thanks in advanced!
December 29, 2010 - 14:47
Hi,oliver
thanks for your amazing ws example.i have run the given project successfully.but when i run the asp page on another pc via safari,the ws does not work.
for example, in browser address, http://192.168.1.1:8080/default.aspx
and ws textbox is ws://192.168.1.1:8181
my pc ip address is 192.168.1.1 and i have configed the aspx page in my IIS.
January 7, 2011 - 19:19
I’ll write it down in my to do list.
Cheers!
January 7, 2011 - 19:20
Lots of things could be going on. If you could provide some more information, I might be able to give you a hand …
January 25, 2011 - 14:36
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material