HTML and CSS Reference
The PerformHandshake() method creates a NetworkStream object passing in the Socket object to its
constructor. This is the new socket that was created for this connection. It uses a StreamReader object to read the
incoming data and later uses a StreamWriter to send data back. By creating these inside nested using statements
you won't have to worry about disposing them. Keep in mind that the handshaking is done using http protocol so
the reading and sending of data does not use the WebSocket frames.
The StreamReader object is used to read the input, one line at a time. You don't need any of this data
because, for this exercise, we're assuming the correct protocol is being requested. In a more general case,
however, you may need to support multiple protocols so you will need to read and interpret what is being sent in.
You will need the request key, however, so this is extracted from the appropriate input line.
The response key is then concatenated with a special guid value. This is documented in the Version 13
specification ( http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-13.txt ). The resulting
string is then encrypted using the SHA1 algorithm. Finally, the StreamWriter object is used to
send back the response including the generated key.
Add the onConnect() event handler using the code in Listing 13-3.
Listing 13-3. Implementing the OnConnect() event handler
private void OnConnect(IAsyncResult asyn)
// create a new socket for the connection
// Perform the necessary handshaking
// Create a WsConnection object for this connection
WsConnection client=new WsConnection(socket);
// Wire-up the event handlers
client.MessageReceived += new MessageReceivedEventHandler(MessageReceived);
client.Disconnected += new WsDisconnectedEventHandler(Disconnected);
// Listen for more connections
_listener.BeginAccept(new AsyncCallback(OnConnect), null);
The OnConnect() method gets a new Socket for this connection by calling the EndAccept() method. It
calls the PerformHandshake() method and creates a WsConnection class, which you will implement next. It then
connects the event handlers so the WsServer object will be notified when a message is received or the connection
is closed. Finally, BeginAccept() is called again to listen for more connections.
In the Solution Explorer, right-click the WsServer project and select the Add ➤ Class
links. Enter WsConnection.cs for the class name.
Enter the code shown in Listing 13-4 as the initial implementation for this class.
Listing 13-4. Implementing the WsConnection class