Simple. Net-based websocket instance-establish a connection

Source: Internet
Author: User
Tags net websocket visual studio 2010
Among the new HTML5 features, I was most excited by websocket. Among the reasons for learning Silverlight, this was also very important. I used to take a preliminary look at the basic principles and it was quite easy to implement. I took a short time in the past two days and tried to write it. I still encountered several problems, summarize the basic information for future or interested friends. My machine environment: Windows 7/Visual Studio 2010 SP1 C #/Google Chrome's article on websocket principles can be found on the Internet, but let people do not know a lot, these are I think I have some help, also stay, for you to view, and here to the author thanks: http://www.zendstudio.net/archives/websocket-protocol/http://songpengfei.iteye.com/blog/1178310http://zh.wikipedia.org/wiki/WebSocket

Http://blog.csdn.net/fenglibing/article/details/6852497

Http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10

A preliminary summary of the process: the client initiates a connection request and sends a message to the server in the following format: Get/HTTP/1.1
Upgrade: websocket
Connection: Upgrade
HOST: 192.168.1.36: 8050
Sec-websocket-origin: http: // localhost: 5113
Sec-websocket-key: yzgrbqbf5a5uwll/n8/R + q =
Sec-websocket-version: 8 after the server receives the message, it returns the message in the following format: HTTP/1.1 101 web SOCKET protocol handshake
Upgrade: websocket
Connection: Upgrade
Sec-websocket-accept: eailq5var3 + ajmxvsqnnoxuc3su =
Websocket-origin: http: // localhost: 5113
Websocket-location: WS: // 192.168.1.36: 8050 after calculation, the server sends the sec-websocket-Key (yzgrbqbf5a5uwll/n8/R + q =) sent by the client, obtain an SEC-websocket-accept (eailq5var3 + ajmxvsqnnoxuc3su =) and return it to the customer. This is actually a handshake process. Once the authentication passes, a real socket connection is established, data can be transmitted normally. After learning about this process, it is relatively easy to develop the server. For the accept algorithm in this version, it may be a process that only people who are new to it do not want to see, but must, fortunately, I found it online and developed a special handshake class to simplify usage. The Code is as follows:

Public class handshake
{

// Key-value pairs used to save the request string
Private hashtable keyvalues;

/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "request"> request string </param>
Public handshake (string request)
{
// Initialize the hash table
Keyvalues = new hashtable ();

// Split the string to separate each line
String [] separator1 = {"\ r \ n "};
String [] rows = request. Split (separator1, stringsplitoptions. removeemptyentries );
Foreach (string row in rows)
{
// ':' Index of the first matching item in each row
Int splitindex = row. indexof (':');
If (splitindex> 0)
{
// Is a key-value pair, saved to the hash table
String key1 = row. substring (0, splitindex). Trim (); // key
String value1 = row. substring (splitindex + 1). Trim (); // Value
Keyvalues. Add (key1, value1); // save it to the keyvalues hash table.
}
}
}

/// <Summary>
/// Return verification code
/// </Summary>
Public String keyaccept
{
Get
{
String secwebsocketkey = getvalue ("Sec-websocket-key ");
String m_magic = "258eafa5-e914-4710995ca-c5ab0dc85b11 ";
Return convert. tobase64string (sha1.create (). computehash (encoding. ASCII. getbytes (secwebsocketkey + m_magic )));
}
}

/// <Summary>
/// Obtain the corresponding value based on the key
/// </Summary>
/// <Param name = "key"> key </param>
/// <Returns> </returns>
Public String getvalue (string key)
{
// Check whether the corresponding key value exists in the hash table
If (keyvalues. containskey (key ))
Return keyvalues [Key]. tostring ();
Else
Return string. Empty; // no matching key value
}
 
/// <Summary>
/// Response string
/// </Summary>
Public String response
{
Get
{
Stringbuilder response = new stringbuilder (); // response string
Response. append ("HTTP/1.1 101 web SOCKET protocol handshake \ r \ n ");

// Convert the key value of the request string to the key value of the corresponding response string and add it to the response string
Response. appendformat ("upgrade: {0} \ r \ n", getvalue ("Upgrade "));
Response. appendformat ("connection: {0} \ r \ n", getvalue ("connection "));
Response. appendformat ("Sec-websocket-accept: {0} \ r \ n", keyaccept );
Response. appendformat ("websocket-origin: {0} \ r \ n", getvalue ("Sec-websocket-origin "));
Response. appendformat ("websocket-location: {0} \ r \ n", getvalue ("host "));

Response. append ("\ r \ n ");

Return response. tostring ();
}
}
}

Key code of the Client: function connect (){
Try {
VaR readystatus = new array ("connecting", "established connection", "Closing connection", "Closing connection ");
VaR host = "WS: // 192.168.1.36: 8050 ";
Conn = new websocket (host );
VaR message = Document. getelementbyid ("message ");
Message. innerhtml + = "<p> socket status:" + readystatus [conn. readystate] + "</P> ";
Conn. onopen = function (){
Message. innerhtml + = "<p> socket status:" + readystatus [conn. readystate] + "</P> ";
}

Conn. onmessage = function (MSG ){
Message. innerhtml + = "<p> receive message:" + MSG. Data + "</P> ";
}

Conn. onclose = function (event ){
Message. innerhtml + = "<p> socket status:" + readystatus [conn. readystate] + "</P> ";
}

}
Catch (exception ){
Message. innerhtml + = "<p> An error occurred. </P> ";
}
} In this way, you can try it. A Web Application Based on native socket support takes its first step. Next, I will implement a chat room for simple communication. Please note: A simple instance Based on. NET websocket-Data Format

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.