INTERNET APPLICATION DEVELOPMENT
MID MARKET ERP DEVELOPMENT
by Jacky Xu
A WebSocket connection is established by an HTTP handshake (prefixed by "ws://" or "wss://") between the client and the server.
The client sends a request:
Then the server sends a response to accept the connection:
"Sec-WebSocket-Key" and "Sec-WebSocket-Accept" are used for confirming the connection between the client and the server through an algorithm of key validation. The client uses "Sec-WebSocket-Version" to tell the server which version of the protocol is supported on the client side. No backward compatibility is required in the standard. The server could send a version list through this header if the client specified version is not supported by the server. "13" (1.3) is a milestone version of WebSocket. "Sec-WebSocket-Protocol" is used to confirm the customized sub-protocol of the connection. This enables both selecting a sub-protocol from the client side and being sure that the server agreed to serve that sub-protocol.
Below is a sample project with MVC 4:
1. Create a new project
2. Add package Microsoft.WebSockets
3. Add a websocket handler class.
In this sample I created a class “Transaction”. It will send a message to client after a timed interval.
4. Add a new Get method to web api controller:
5. To avoid server timeout issue, add some code in global.asax.cs.
And that completes the server side code. Let’s continue to the client side.
6. Add some code to index.cshtml.
7. The Open button opens the WebSocket connection. The Close button closes the WebSocket connection. The Send button sends a message to the server and the server sends a message to the client during the processing period. Then the client processes the received message.
8. Now let’s try it.
9. I’m using two web browsers to simulate multiple user connections.
It’s a connection through Chrome.
Then I open IE to create another connection. After creating this connection, we can see the online user auto-refreshed and it doesn’t affect “Test Processing.”
Try it and see if it works for you.