HTML and CSS Reference
In-Depth Information
manages this connection is passed to the event handler. This code uses its SendMessage() method to send
an echo back. The Disconnected() event handler, removes this connection from its active list and displays a
message to the console window.
4.
Add the PerformHandshake() method using the code shown in Listing 13-2.
Listing 13-2. Implementing the handshaking protocol
private void PerformHandshake(Socket s)
{
using (NetworkStream stream=new NetworkStream(s))
using (StreamReader reader=new StreamReader(stream))
using (StreamWriter writer=new StreamWriter(stream))
{
string key="";
// Read the input data using the stream reader, one line
// at a time until all lines have been processed. The only
// item that we need to get is the request key.
string input="Empty";
while (!string.IsNullOrWhiteSpace(input))
{
input=reader.ReadLine();
if (input !=null &&
input.Length>18 &&
input.Substring(0, 18) == "Sec-WebSocket-Key:")
// Save the request key
key=input.Substring(19);
}
// This guid is used to generate the response key
const String keyGuid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string webSocketAccept;
// The response key in generated by concatenating the request
// key and the special guid. The result is then encrypted.
string ret=key+keyGuid;
SHA1 sha=new SHA1CryptoServiceProvider();
byte[] sha1Hash=sha.ComputeHash(Encoding.UTF8.GetBytes(ret));
webSocketAccept=Convert.ToBase64String(sha1Hash);
// Send handshake response to the client using the
// stream writer
writer.WriteLine("HTTP/1.1 101 Switching Protocols");
writer.WriteLine("Upgrade: websocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("Sec-WebSocket-Accept: "+webSocketAccept);
writer.WriteLine("");
}
}
 
Search WWH ::




Custom Search