Websocket - Server Using HttpListener and Client With ClientWebSocket

Introduction

In the previous article, we saw how to host Websocket service as windows service.

This time, we will learn the use of the low-level HttpListener class (System.Net.HttpListener), to start a self-hosted service. And the client we will be using is ClientWebSocket (System.Net.WebSockets).

Environment : VS Professional 2012 RC, Windows 8 Server

I will break down this article into the following 2 simple steps:

  • Server - HttpListener
  • Client - ClientWebSocket

A. Server - HttpListener

  1. Create a new Project; Windows -> Console Application
    Solution Name : WebsocketHttpListener
    Project Name: Server
  2. Add a new class (WebsocketServer.cs) to the Server project
  3. Start the HttpListener, and continually process the requests received
websocket1.gifwebsocket1a.gif
  1. Process received request
websocke2.gif
  1. Invoke Start, from the Main program thread
websocket3.gif

B. Client- ClientWebSocket

  1. Add new Project (Windows -> Console Application) Client to the solution.
  2. Connect to the listener at the same endpoint to which its listening; the only difference is the protocol over which you are connecting (i.e. WS).
websocket4.gif
  1. Once connected, write Send and Receive async Tasks.
websocket5.gif

Build the solution.

Update the solution properties, so that it runs both applications (Server first and then Client).

websocke6.gif

Run to test. (Make sure that you are running Visual Studio under Administrative rights.)

websocke7.gif

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now