HTML and CSS Reference
In-Depth Information
This code shows a generic handler—
WebSocketGenericHandler
—that triggers the Web Socket server.
The generic handler's
ProcessRequest()
method first checks whether the incoming request is a Web Socket
request. It does so by checking the
IsWebSocketRequest
property of the
HttpContext
object. This property
works hand in hand with the IIS 8.0 WebSocket module and returns
true
if an incoming request is a
WebSocket request. A WebSocket request is different than an ordinary HTTP request in that instead of
using the
http://
protocol it uses the
ws://
(WebSocket) protocol. For example, a WebSocket request to
this generic handler looks like this:
ws://localhost:49428/WebSocketGenericHandler.ashx
If
IsWebSocketRequest
returns
true
, the
AcceptWebSocketRequest()
method of the
HttpContext
is
called. This method takes one parameter—a
user
function—that supplies a function that listens and
responds to the client requests. In this case, the
EchoServer
function contains the logic to listen to the
incoming data and echo it to the client. The
user
function supplied to the
AcceptWebSocketRequest()
method should be an asynchronous function, as shown in Listing 11-16.
Listing 11-16.
EchoServer Asynchronous Function
public async Task EchoServer(AspNetWebSocketContext context)
{
WebSocket socket = context.WebSocket;
while (true)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await
socket.ReceiveAsync(buffer, CancellationToken.None);
if (socket.State == WebSocketState.Open)
{
string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
userMessage = “You sent: “ + userMessage + “ at “ +
DateTime.Now.ToLongTimeString();
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
await socket.SendAsync(buffer, WebSocketMessageType.Text,
true, CancellationToken.None);
}
else
{
break;
}
}
}
The
EchoServer()
method is marked as
async
, indicating that the code inside it runs in asynchronous
fashion. An
async
method is a convenient way to execute a long-running operation without blocking the
main thread. In this example, the Echo server is supposed to continuously listen for incoming requests—
that is, a long-running operation.
EchoServer()
returns a
Task
object. The
Task
class acts as a wrapper to
the asynchronous code.
EchoServer()
receives a parameter of type
AspNetWebSocketContext
. The
AspNetWebSocketContext
class gives you access to the
WebSocket
through its
WebSocket
property. The
WebSocket
class is the server-side counterpart of the HTML5
WebSocket
object. An endless
while
loop is
then started so the Echo server can continuously listen to incoming requests.
To receive incoming data, you use the
WebSocket
class's
ReceiveAsync()
method. This method is
invoked along with the
await
operator. The
await
operator indicates that the execution of the calling