Skip to main content

Explore Kaazing Websocket in .Net

Introduction

Kaazing WebSocket Gateway provides full duplex web communication. It provides an alternate way of communication from server to client for “polling” or “long-polling”.

WebSocket

WebSocket is a full-duplex single socket connection over which messages can be sent between a client and a server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management.

Kaazing WebSocket

Kaazing WebSocket Gateway is an HTML5-compliant WebSocket server with support to today's pre-HTML5 browsers. The Gateway provides a bridge between WebSocket clients and your back-end systems, servers, and applications. This enables you to implement your own custom protocol or run an existing protocol over WebSocket.

Installing Kaazing WebSocket

1.       Kaazing WebSocket can be installed in Windows 7, Windows Vista, Windows XP SP3
2.       Download the full Kaazing WebSocket Gateway - HTML5 Edition from the Kaazing download page.
3.       There are two type of download available
a.       Base: Contains a minimal download of the Gateway for experienced users who are ready to use the Gateway in production.
b.      Full: Contains the Base download plus the Gateway documentation and the services needed to run the Gateway demos.
4.       Unpack the Kaazing WebSocket Gateway distribution into a directory of your choice (for example, C:\kaazing or /home/username/Kaazing). Unpacking the distribution creates a directory containing the Gateway; this directory is referred to as GATEWAY_HOME in the documentation.
5.       On Windows you can use an Unzip program to unpack the Gateway *.zip file
6.       Start the demo services by navigating to the GATEWAY_HOME/bin directory and running the demo-services.start.bat (Windows) script.
a.       To start the demo service in Windows Explorer, navigate to the GATEWAY_HOME/bin directory where you installed the Gateway
b.      Use the following command to start the demo services, and substitute either the public IP address or the public DNS name for example.com:
           demo-services.start.bat udp://example.com:50505
7.       Start Kaazing WebSocket Gateway by navigating to the GATEWAY_HOME/bin directory and running the gateway.start.bat (Windows) script.
a.       To start the gateway on Windows ; In Windows Explorer, navigate to the GATEWAY_HOME/bin directory where you installed the Gateway.
b.      Double-click the gateway.start.bat script.
8.       Verify the Gateway setup by navigating to http://localhost:8001/ in your browser.
9.       Verify Gateway
a.       To verify that the Gateway is up and running, open a browser and access the Gateway home page at http://localhost:8001/. Click the Documentation tab to see the documentation library and learn more about the Gateway. Click the Demos tab to view the demos.
b.      A WebSocket Echo demo service is bundled and started by default in the Full product. If you want to configure your own back-end service, see the Advanced configuration service and the client how-to guides on the Kaazing Documentation home page for more information.
c.       See the Release Notes (online only) for an overview of the certified browser versions for this release.
You are now done setting up Kaazing WebSocket Gateway locally.
Note:

When running the com.kaazing.gateway.client.dotnet.core.demo.exe demo for dotnet from GATEWAY_HOME/ demo/dotnet/bin/Release then exception is thrown as “Cannot load the System.Net assembly”.
In order to resolve this error you have to download .NET Framework 4 update from this url http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3556.

Configuring Kaazing WebSocket Gateway to use Multicast

To Multicast we have to specify the multicast URI (an IP address with the multicast address mask of 224.0.0.0) in the accept property.

The following is an example of a service configuration element in the file GATEWAY_HOME/conf/gateway-config.xml for a service using a multicast address. In this example, data packets sent to the multicast group 224.0.0.1:50505 (shown in line 8) will be broadcast to all clients connected to sse://localhost:8000/sse or sse+ssl://localhost:9000/sse.






To verify this configuration, you can start the newsfeed data source that ships with the Kaazing WebSocket Gateway bundle and pass the multicast URI you have configured as a startup argument. To do this, perform the following steps:
In a command prompt or shell, navigate to GATEWAY_HOME/bin.
Run gateway.demos.start mcp://multicast-uri:port-number (for example, gateway.demos.start mcp://224.0.0.1:50505) to start the newsfeed data source.
Run gateway.start to start the Gateway.
In a browser, navigate to the server-sent events demo page (by default, this is located at http://localhost:8001/demo/sse.html) and watch the streaming news feed data.
You can now configure and run a second Kaazing WebSocket Gateway to serve server-sent event streams from a different host and port for the same newsfeed multicast data packets. Note that services cannot send UDP packets to an MCP acceptor, nor MCP packets to a UDP acceptor.

After configuring the gateway create .Net console server application and add below listed code in your server application.

private void MultiCastMessage()
{
      Console.WriteLine("Start Transmitting the message ");
      Console.WriteLine("");
      Console.Read();

      UdpClient udpClient = new UdpClient();
      try
      {
          string hName = Dns.GetHostName();
          var address = Dns.GetHostAddresses(hName);
          udpClient.Connect(new IPEndPoint(address[1], 50505));
        
          List<String> messages = new List<string>();
          messages.Add("Sending message from  Origin(Server).");

          Byte[] msgByte = default(Byte[]);
          foreach (String msg in messages)
          {
              Console.WriteLine("Sending Message ......... ");
              Console.WriteLine(msg);
              System.Threading.Thread.Sleep(1000);

              msgByte = Encoding.ASCII.GetBytes(msg);
              int i = udpClient.Send(msgByte, msgByte.Length);

              System.Threading.Thread.Sleep(3000);

              Console.WriteLine("----------------------------------------------");
          }
          Console.WriteLine("");
          Console.WriteLine("Completed Transmitting the message ");

          udpClient.Close();
          Console.ReadLine();
     }
     catch (Exception ex)
     {
        Console.WriteLine("Error : " + ex.Message);
     }
}

In Main method of your console application call method MultiCastMessage()

static void Main(string[] args)
{
     MultiCastMessage();
}

Create Windows Form Client application to send and receive messages.

  • Add Reference to com.kaazing.gateway.client.html5.dll”
  • Include in your code as “using com.kaazing.gateway.client.html5;”
  • Set the default location as  String defaultLocation = "http://localhost:8001/sse";

 Add HandleLog method to client application

private void HandleLog(String message)
{
     this.BeginInvoke((InvokeDelegate)(() =>
     {
        Log("LOG: " + message);
     }));
}

Add “Connect ” button and add code for ConnectButton_Click event

private void ConnectButton_Click(object sender, EventArgs e)
{
      // Immediately disable the connect button
      ConnectButton.Enabled = false;
      eventSource = new EventSource();
      Log("CONNECT:" + LocationText.Text);

      eventSource.OpenEvent += new OpenEventHandler(OpenHandler);
      eventSource.ErrorEvent +=new ErrorEventHandler(ErrorHandler);
      eventSource.MessageEvent += new MessageEventHandler(MessageHandler);

      eventSource.Connect(LocationText.Text);
}

Add “Disconnect ” button and add code for DisconnectButton_Click event

private void DisconnectButton_Click(object sender, EventArgs e)
{
       Log("DISCONNECTED");
       eventSource.Disconnect();
       ConnectButton.Enabled = true;
 }

Add LOG_LIMIT  and logLines Variables

private const int LOG_LIMIT = 50;
private Queue<string> logLines = new Queue<string>();

Add Log method

private void Log(string arg)
{
    logLines.Enqueue(arg);
    if (logLines.Count > LOG_LIMIT)
    {
         logLines.Dequeue();
    }
    string[] o = logLines.ToArray<string>();

    o = o.Reverse<string>().ToArray<string>();

    Output.Text = string.Join("\r\n", o);
}

Add “ClearLogButton ” button and add code for ClearLogButton_Click event

private void ClearLogButton_Click(object sender, EventArgs e)
{
     logLines.Clear();
     Output.Text = "";
}

Add  code for OpenHandler

private void OpenHandler(object sender, OpenEventArgs args)
{
    this.BeginInvoke((InvokeDelegate)(() =>
    {
        Log("CONNECTED");

        DisconnectButton.Enabled = true;
    }));
}

Add  code for MessageHandler

private void MessageHandler(object sender, MessageEventArgs args)
{
     string messageData = args.Data;
     string origin = args.Origin;
     string lastEvent = args.EventId;

     this.BeginInvoke((InvokeDelegate)(() =>
     {
          Output.Text = Output.Text + Environment.NewLine + " Recieved : " +
          messageData + Environment.NewLine + "-----";
     }));
}

Add code for ErrorHandler

private void ErrorHandler(object sender, ErrorEventArgs args)
{
    this.BeginInvoke((InvokeDelegate)(() =>
    {
        Exception ex = args.GetException;
        Output.Text = ex.InnerException.ToString();
    }));
}

  
1.       Start Kaazing WebSocket Gateway by navigating to the GATEWAY_HOME/bin directory and running the gateway.start.bat (Windows) script.

     

2.       Start Server application



3.       Start Client application

       


4.       In Client App Conncet to Gateway by clicking on “Connect” button.
5.       From Client App Send a message from Client App



As you can see in above screen shot client received the message sent from server.

Comments

Popular posts from this blog

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         }     }     public class Student : IDoWork     {         public string DoWork()         {             return "Study in school" ;         }     } This class will actually create an instance of the concrete class so that you can work on that        object further     public class FactoryDemo     {         public T Create

How to enable windows authentication in PostgreSQL

1.     Steps to create user or role in PostgreSQL ·         Open pgAdmin III ·         Login to PostgreSQL database ·         Select “Login Roles” and right click on mouse to view the context menu ·         Select “New Login Role” from context menu ·         Enter desired user name in “Role name” text box ·         Select “Definition” tab in “New Login Role” window ·         Enter desired Password in the given text box ·         Select “Role privileges” tab in “New Login Role” window ·         Select the privileges for the entered user or role ·         Select “SQL” tab in “New Login Role” window ·         This will display the auto generated script ·         Review the script and click on “OK” button ·         Now in the “Login Roles” the newly created role or user “newUser” is displayed ·         Now in pgAdmin III object browser select the database to which the newly created user should be ma

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete University cl