WebSocket Extension for CSHTML5

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

WebSocket Extension for CSHTML5

Postby JS-Support @Userware » Fri Feb 26, 2016 11:44 am

Dear CSHTML5 users,

I am pleased to inform you of the release of this extension that adds WebSocket support to CSHTML5.

It requires CSHTML5 v1.0 Beta 7.2 or newer.

To use, simply add a new class named "WebSocket.cs" to your project, and copy/paste the following code:

Code: Select all

using System;

//------------------------------------
// This extension adds WebSocket support to C#/XAML for HTML5 (www.cshtml5.com)
//
// It requires Beta 7.2 or newer.
//
// This project is licensed under The open-source MIT license:
// https://opensource.org/licenses/MIT
//
// Copyright 2016 Userware / CSHTML5
//------------------------------------

namespace CSHTML5.Extensions.WebSockets
{
    public class WebSocket
    {
        object _referenceToTheJavaScriptWebSocketObject;

        public event EventHandler OnOpen;
        public event EventHandler OnClose;
        public event EventHandler<OnMessageEventArgs> OnMessage;
        public event EventHandler<OnErrorEventArgs> OnError;

        public WebSocket(string uri)
        {
            _referenceToTheJavaScriptWebSocketObject = CSHTML5.Interop.ExecuteJavaScript("new WebSocket($0)", uri);

            CSHTML5.Interop.ExecuteJavaScript(
                    @"$0.onopen = $1;
                      $0.onclose = $2;
                      $0.onmessage = $3;
                      $0.onerror = $4",
                _referenceToTheJavaScriptWebSocketObject,
                (Action<object>)this.OnOpenCallback,
                (Action<object>)this.OnCloseCallback,
                (Action<object>)this.OnMessageCallback,
                (Action<object>)this.OnErrorCallback);
        }

        public void Send(string message)
        {
            CSHTML5.Interop.ExecuteJavaScript("$0.send($1)", _referenceToTheJavaScriptWebSocketObject, message);
        }

        public void Close()
        {
            CSHTML5.Interop.ExecuteJavaScript("$0.close()", _referenceToTheJavaScriptWebSocketObject);
        }

        void OnOpenCallback(object e)
        {
            if (this.OnOpen != null)
                OnOpen(this, new EventArgs());
        }

        void OnCloseCallback(object e)
        {
            if (this.OnClose != null)
                OnClose(this, new EventArgs());
        }

        void OnMessageCallback(object e)
        {
            string data = string.Empty;
           
            if (!Convert.ToBoolean(CSHTML5.Interop.ExecuteJavaScript("(typeof $0 === 'undefined')", e)))
                data = Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("$0.data", e));

            if (this.OnMessage != null)
                OnMessage(this, new OnMessageEventArgs(data));
        }

        void OnErrorCallback(object e)
        {
            string data = string.Empty;
           
            if (!Convert.ToBoolean(CSHTML5.Interop.ExecuteJavaScript("(typeof $0 === 'undefined')", e)))
                data = Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("$0.data", e));

            if (this.OnError != null)
                OnError(this, new OnErrorEventArgs(data));
        }
       
        public ReadyState ReadyState
        {
            get
            {
                int readyStateInt = Convert.ToInt32(CSHTML5.Interop.ExecuteJavaScript(@"$0.readyState", _referenceToTheJavaScriptWebSocketObject));
                return (ReadyState)readyStateInt;
            }
        }
    }

    public class OnMessageEventArgs : EventArgs
    {
        public readonly string Data;

        public OnMessageEventArgs(string data)
        {
            this.Data = data;
        }
    }

    public class OnErrorEventArgs : EventArgs
    {
        public readonly string Data;

        public OnErrorEventArgs(string data)
        {
            this.Data = data;
        }
    }
   
    public enum ReadyState : int
    {
        /// <summary>
        /// The connection is not yet open.
        /// </summary>
        CONNECTING = 0,
        /// <summary>
        /// The connection is open and ready to communicate.
        /// </summary>
        OPEN = 1,
        /// <summary>
        /// The connection is in the process of closing.
        /// </summary>
        CLOSING = 2,
        /// <summary>
        /// The connection is closed or couldn't be opened.
        /// </summary>
        CLOSED = 3
    }
}



The extension works by wrapping the JavaScript "WebSocket" class into a C#/XAML class for consumption by CSHTML5-based apps.


You can test the code by calling the following C# method:

Code: Select all

void TestWebSockets()
{
    //------------------------------------------------
    // This test calls the "Echo" service provided by http://www.websocket.org/echo.html
    //------------------------------------------------

    var webSocket = new CSHTML5.Extensions.WebSockets.WebSocket("ws://echo.websocket.org/");
    webSocket.OnMessage += (s, e) => MessageBox.Show("RESPONSE: " + e.Data);
    webSocket.OnError += (s, e) => MessageBox.Show("ERROR: " + e.Data);
    webSocket.OnClose += (s, e) => MessageBox.Show("WebSocket Closed");
    webSocket.OnOpen += (s,e) =>
        {
            MessageBox.Show("WebSocket Opened");

            // Send a message to the Echo service, which will respond with the same message:
            webSocket.Send("CSHTML5 rocks!");
        };
}



Regards,
JS-Support

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5 /readyState of underlying javascript websocket object

Postby Sesztak » Mon Aug 01, 2016 12:01 pm

Dear JS-Support,
Is there any way to get info about readyState of underlying javascript websocket object, like:

Constant Value Description
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.

https://developer.mozilla.org/en-US/doc ... /WebSocket

Thanks for your kind reply in advance,
Best Regards,
Péter

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Wed Aug 03, 2016 2:03 am

Dear JS-Support,

In the meantime we have written our extension to your solution as follows -please, check it.
I hope it helps others:

Add the following method to WebSocket.cs:
public int Get_readyState()
{
var _readyState = CSHTML5.Interop.ExecuteJavaScript (@"$0.readyState", _referenceToTheJavaScriptWebSocketObject);

/* CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.
*/
return Convert.ToInt32(_readyState);
}

Usage:
E.g. when you try to reconnect the Client to WebSocket Server (internet connection lost, wifi off, ISP temp. broken, etc.) you should check the readyState of you websocket connection before re-init you client WebSocket object, pseudo code -called from a _dispatcherTimerForWebSocketServiceReconnection_Tick:

var rs = webSocketService_ServerTime.Get_readyState();
if (rs == 3) // CLOSED 3 The connection is closed or couldn't be opened.
{
webSocketService_ServerTime = new CSHTML5.Extensions.WebSockets.WebSocket(websocketServiceFullURI_WebSocketService_ServerTime);
webSocketService_ServerTime.OnOpen += WebSocketService_ServerTime_OnOpen1;
webSocketService_ServerTime.OnMessage += WebSocketService_ServerTime_OnMessage1;
webSocketService_ServerTime.OnClose += WebSocketService_ServerTime_OnClose1;
webSocketService_ServerTime.OnError += WebSocketService_ServerTime_OnError1;
}

I hope it helps other,

Best Regards,
Péter

xidea
Posts: 33
Joined: Thu Jun 30, 2016 7:04 pm

Re: WebSocket Extension for CSHTML5

Postby xidea » Wed Aug 03, 2016 11:12 am

Thanks for sharing, Péter. I was dealing with same thing.

What I think has no solution is server side. No way to catch a Websocket connection event in WCF prior the connection is in the "opened" state.

Flavio

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Wed Aug 03, 2016 11:34 am

Dear Flavio,

your welcome, if you need more help just mention.

for your kind information:
-if you would like to get more information about server - multi clients port states, it should be a nice help:
TCPView
https://technet.microsoft.com/en-us/sys ... s/bb897437
(similar to netstat but much more quicker to use because of UI)

e.g. if you have to watch, close ports/kill process manually several times.

-we use both WCF and WebSocket in the same solution mixed -no problem at all.
but Interestingly: we not using the MicroSoft WebSocket part of WCF, but we using 3rd party WebSocket lib for Server:
websocket-sharp :
https://github.com/sta/websocket-sharp

it works perfectly with client side (CSHTML5 WebSocket wrapper of javascript native WebSodket).

have a nice day (or night) !,
Best Regards,
Péter

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5 + online / offline status FROM Client side

Postby Sesztak » Thu Aug 04, 2016 3:33 am

Dear Flavio,

if you want to check online / offline status FROM Client side (not only by OnClosed Server emitted event as prev. mentioned) as well, you should use the following extension method written by us:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSHTML5.Extensions.CheckClientOnlineStatusBynavigatoronLine
{
public class CheckClientOnlineStatusBynavigatoronLine
{
public event EventHandler OnOnLine;
public event EventHandler OnOffLine;

public CheckClientOnlineStatusBynavigatoronLine()
{


CSHTML5.Interop.ExecuteJavaScript(
@"window.addEventListener('online', $0);
window.addEventListener('offline', $1)",

(Action<object>)this.OnOnLineCallback,
(Action<object>)this.OnOffLineCallback
);
}

void OnOnLineCallback(object e)
{
if (this.OnOnLine != null)
OnOnLine(this, new EventArgs());
}

void OnOffLineCallback(object e)
{
if (this.OnOffLine != null)
OnOffLine(this, new EventArgs());
}

}
}



Usage:
1./ instantiates the object, e.g.:

CSHTML5.Extensions.CheckClientOnlineStatusBynavigatoronLine.CheckClientOnlineStatusBynavigatoronLine
_CheckClientOnlineStatusBynavigatoronLine = new CSHTML5.Extensions.CheckClientOnlineStatusBynavigatoronLine.CheckClientOnlineStatusBynavigatoronLine();

2./ add event handlers, e.g. :
_CheckClientOnlineStatusBynavigatoronLine.OnOnLine += _CheckClientOnlineStatusBynavigatoronLine_OnOnLine;
_CheckClientOnlineStatusBynavigatoronLine.OnOffLine += _CheckClientOnlineStatusBynavigatoronLine_OnOffLine;

3./ handle the OnOnLine and OnOffLine according your needs.
E.g. OnOffLine : start reconnect process.

Important !!: the above mentioned technique ONLY checks that the client has or not connection,
but NOT CHECK the server availability directly / de facto.

E.g. if your client is behind the WIFI router, and the connection is okay TILL router (from client to router), and Router <> Internet Connection has broken: you will get ONLINE status.
(what should be misleading -depending on your use case).

If you want much more direct control -I mean to check client - server connection actually/de facto -, see the following clever notes :
https://www.kirupa.com/html5/check_if_i ... script.htm

Best Regards,
Péter

Black-Byte
Posts: 17
Joined: Fri Jan 29, 2016 2:05 am

Re: WebSocket Extension for CSHTML5

Postby Black-Byte » Fri Oct 28, 2016 5:08 am

Hi,

i'm seeking for an working example at the server side without IIS. The last one i tried was this one http://www.c-sharpcorner.com/uploadfile/bhushanbhure/websocket-server-using-httplistener-and-client-with-client/. But unfortunately it doesn't work. The connection goes up and after first sending i got an exception on server side with a closed event on client side. I've tried different solutions but i don't get one running. So has someone a good example ? (Orginal i tried to get it running with https://www.frozenmountain.com/products/websync but that looks more complicated)

Greets

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Fri Oct 28, 2016 5:54 am

Dear Black-Byte,

it's easy:

Prerequisites:
-first of all you need two Windows computers, preferably not on the same LAN (e.g. one at your side, and another from your friend or at other place, e.g. in another city, Visual Studio installed on both, and use Remote Desktop or TeamViewer to program the other : remote PC).
-just for an example:
let the remote PC is Server, and let your PC is a Client with CSHTML5 solution.
-at the Server side (if you do not have registered web site by DNS or not having static IP address of the Server) :
**check the public IP address of Server, e.g. with https://whatismyipaddress.com/
**configure the router (Server side) port forwarding: e.g. 12345 => 12345 (check it: any unused, free port should be ok.)

At Server side:
-make a WPF C# solution, add a nuget reference (References => Manages NuGet Packages => browse (include prerelease !) : WebSocketSharp = > install it.)

code:
public static WebSocketServer _webSocketServer;
_webSocketServer = new WebSocketServer(12345);
_webSocketServer.AddWebSocketService<WebSocketService_ServerTime>("/WebSocketService_ServerTime"); // important: you have to make your own class inherited from WebSocketBehavior, e.g.: public class WebSocketService_ServerTime : WebSocketBehavior{...}
_webSocketServer.Start();

(you can Stop websocket server at your program close: _webSocketServer.Stop();)

To send something by _webSocketServer :
var hosts = _webSocketServer.WebSocketServices.Hosts;
var sessions = hosts.ElementAt(0).Sessions; // sessions = {WebSocketSharp.Server.WebSocketSessionManager}
// 0 -means the zero index, as you add only one websocket service by _webSocketServer.AddWebSocketService..
sessions.Broadcast("hello everybody from Server !");

for more documentation: see https://github.com/sta/websocket-sharp , Usage part.

At Client Side: CSHTML5:
CSHTML5.Extensions.WebSockets.WebSocket webSocketService_ServerTime;

Somewhere init: (under PageLoaded event e.g.)
webSocketService_ServerTime = new CSHTML5.Extensions.WebSockets.WebSocket("ws://YOURSERVERIPADDRESS:12345"); // ip address + port number

webSocketService_ServerTime.OnOpen += WebSocketService_ServerTime_OnOpen1;
webSocketService_ServerTime.OnMessage += WebSocketService_ServerTime_OnMessage1;
webSocketService_ServerTime.OnClose += WebSocketService_ServerTime_OnClose1;
webSocketService_ServerTime.OnError += WebSocketService_ServerTime_OnError1;

under OnMessage1 event you can handle / process the data sent by Server:
void WebSocketService_ServerTime_OnMessage1(object sender, CSHTML5.Extensions.WebSockets.OnMessageEventArgs e)
{
// e.Data
}

That's all.

Is is enough to you to run / setp-up the basic comm. ?
(note: advisable to start your server code in Admin mode)

Best Regards,
Péter

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Fri Oct 28, 2016 5:58 am

one more thing:
-shut down the Windows Firewall temporary at Server side or configure it to pass your Server through the firewall with 12345 port.
-start both Visual Studio in Admin mode for first tries.

br,
P.

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Fri Oct 28, 2016 6:01 am

at 'configure the router (Server side) port forwarding: e.g. 12345 => 12345' forward this port to your Server DHCP address obviously: e.g. 192.168.0.100

Black-Byte
Posts: 17
Joined: Fri Jan 29, 2016 2:05 am

Re: WebSocket Extension for CSHTML5

Postby Black-Byte » Mon Oct 31, 2016 4:36 am

Hi,

thanks for the good advice.
I should have first search at the nuget library ;). Now it works local. But when im testing with a remote client i got a nullref exception at JSIL.Bootstrap.js line 4222 that outside my code.

To clarify i've made a seperate button to start the connection the page loads and after the button press it shows me a log text that works and short time after that the error appears.

Greets

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Mon Oct 31, 2016 7:33 am

if you need more help, upload your buggy server & client sources.
br, Péter

Black-Byte
Posts: 17
Joined: Fri Jan 29, 2016 2:05 am

Re: WebSocket Extension for CSHTML5

Postby Black-Byte » Mon Oct 31, 2016 7:50 am

Ok,

here is the Client

Code: Select all

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace CXAML_Websocket
{
   public partial class MainPage : Page
   {
      public CSHTML5.Extensions.WebSockets.WebSocket webSocket;

      public MainPage()
      {
         this.InitializeComponent();

         // Enter construction logic here...
         B_Test.Click += new RoutedEventHandler(SU_Button_Test);
         B_Start.Click += new RoutedEventHandler(SU_Button_Start);
      
      }

      private void SU_Button_Test(object sender, RoutedEventArgs e) 
      {
         TB_Click.Text = DateTime.Now.ToLongTimeString();
         webSocket.Send("CSHTML5 rocks!");
      }

      private void SU_Button_Start(object sender, RoutedEventArgs e)
      {
         TB_Websocket.Text += Environment.NewLine + "Start";
            webSocket = new CSHTML5.Extensions.WebSockets.WebSocket("ws://localhost:12345/WebTest/");
         webSocket.OnMessage += (s, ne) => OnMessage(s, ne);
         webSocket.OnError += (s, ne) => OnError(s, ne);
         webSocket.OnClose += (s, ne) => OnClose(s, ne);
         webSocket.OnOpen += (s, ne) => OnOpen(s, ne);
      }

      private void OnMessage(object s, CSHTML5.Extensions.WebSockets.OnMessageEventArgs e)
      {
         TB_Websocket.Text += Environment.NewLine + "RESPONSE: " + e.Data;
      }
      private void OnError(object s, CSHTML5.Extensions.WebSockets.OnErrorEventArgs e)
      {
         TB_Websocket.Text += Environment.NewLine + "ERROR: " + e.Data;
      }
      private void OnClose(object s, EventArgs e)
      {
         TB_Websocket.Text += Environment.NewLine + "WebSocket Closed";
      }
      private void OnOpen(object s, EventArgs e)
      {
         // Send a message to the Echo service, which will respond with the same message:

         TB_Websocket.Text += Environment.NewLine + "WebSocket Opened";
      }
   }
}

Code: Select all

using System;

//------------------------------------
// This extension adds WebSocket support to C#/XAML for HTML5 (www.cshtml5.com)
//
// It requires Beta 7.2 or newer.
//
// This project is licensed under The open-source MIT license:
// https://opensource.org/licenses/MIT
//
// Copyright 2016 Userware / CSHTML5
//------------------------------------

namespace CSHTML5.Extensions.WebSockets
{
   public class WebSocket
   {
      object _referenceToTheJavaScriptWebSocketObject;

      public event EventHandler OnOpen;
      public event EventHandler OnClose;
      public event EventHandler<OnMessageEventArgs> OnMessage;
      public event EventHandler<OnErrorEventArgs> OnError;

      public WebSocket(string uri)
      {
         _referenceToTheJavaScriptWebSocketObject = CSHTML5.Interop.ExecuteJavaScript("new WebSocket($0)", uri);

         CSHTML5.Interop.ExecuteJavaScript(
                 @"$0.onopen = $1;
                      $0.onclose = $2;
                      $0.onmessage = $3;
                      $0.onerror = $4",
             _referenceToTheJavaScriptWebSocketObject,
             (Action<object>)this.OnOpenCallback,
             (Action<object>)this.OnCloseCallback,
             (Action<object>)this.OnMessageCallback,
             (Action<object>)this.OnErrorCallback);
      }

      public void Send(string message)
      {
         CSHTML5.Interop.ExecuteJavaScript("$0.send($1)", _referenceToTheJavaScriptWebSocketObject, message);
      }

      public void Close()
      {
         CSHTML5.Interop.ExecuteJavaScript("$0.close()", _referenceToTheJavaScriptWebSocketObject);
      }

      void OnOpenCallback(object e)
      {
         if (this.OnOpen != null)
            OnOpen(this, new EventArgs());
      }

      void OnCloseCallback(object e)
      {
         if (this.OnClose != null)
            OnClose(this, new EventArgs());
      }

      void OnMessageCallback(object e)
      {
         var data = Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("$0.data", e));

         if (this.OnMessage != null)
            OnMessage(this, new OnMessageEventArgs(data));
      }

      void OnErrorCallback(object e)
      {
         var data = Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("$0.data", e));

         if (this.OnError != null)
            OnError(this, new OnErrorEventArgs(data));
      }
   }

   public class OnMessageEventArgs : EventArgs
   {
      public readonly string Data;

      public OnMessageEventArgs(string data)
      {
         this.Data = data;
      }
   }

   public class OnErrorEventArgs : EventArgs
   {
      public readonly string Data;

      public OnErrorEventArgs(string data)
      {
         this.Data = data;
      }
   }
}

and little gui for 2 buttons + textboxes

and here are the server (vb.net!)

Code: Select all

Public Class Form1
    Private Cloc_WebsocketServer As WebSocketSharp.Server.WebSocketServer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Cloc_WebsocketServer = New WebSocketSharp.Server.WebSocketServer(12345)
            Cloc_WebsocketServer.AddWebSocketService(Of C_WebTest)("/WebTest")
            Cloc_WebsocketServer.Start()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Cloc_WebsocketServer.Stop()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            For Each Loc_Host As WebSocketSharp.Server.WebSocketServiceHost In Cloc_WebsocketServer.WebSocketServices.Hosts
                Dim Loc_Session As WebSocketSharp.Server.WebSocketSessionManager = Loc_Host.Sessions
                Loc_Session.Broadcast("Test")
            Next

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

Code: Select all

Public Class C_WebTest
    Inherits WebSocketSharp.Server.WebSocketBehavior

    Protected Overrides Sub OnMessage(e As MessageEventArgs)
        Send(Now.ToString)
        '    MyBase.OnMessage(e)
    End Sub
End Class

and again only a simple gui with some buttons

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Mon Oct 31, 2016 9:37 am

I will send a full Server & Client source codes in Visual Studio 2015, C#.
(unfortunately, I can't help you in VisualBasic: the last time I'm used it was the first edition of Visual Basic 2002 :))), but I's pretty sure you can translate it to C#.)

give me some minutes ...

Br,
P.

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Mon Oct 31, 2016 10:19 am

I hope, it helps you:

at CSHTML5_WebSocket_Client project, MainPage.xaml.cs, line number 22:
"ws://YOURSERVERIPADDRESS:12345"
change 'YOURSERVERIPADDRESS' to server IP address (doesn't matter if public ip address, like '79.123.101.248' or your registered Domain Name, like 'facebook': you can use both. Do not try to use 'localhost' or similar solutions: it will not work ! )

be,
Péter
Attachments
WebSocket_WPFServer_CSHTML5Client.zip
(1.54 MiB) Downloaded 1640 times

Black-Byte
Posts: 17
Joined: Fri Jan 29, 2016 2:05 am

Re: WebSocket Extension for CSHTML5

Postby Black-Byte » Tue Nov 01, 2016 3:13 am

Sometimes the answer is so close .. i've started the client with ws://localhost:12345 ... naturally when im starting the client on a remote machine it doesn't work. Now with a correct IP it works with my code. I found it after reading your example.
Thanks.

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: WebSocket Extension for CSHTML5

Postby Sesztak » Tue Nov 01, 2016 3:45 am

your welcome :)

Let me emphasize for your help : the real power is at the Server side in the inherited class (or more importantly classes, see bellow) from WebSocketBehavior (in my example : public class WebSocketService_ServerTime).

Why ? :

-you could manage connected clients (boiler plate kind of codes: session IDs, OnOpen(), OnMessage(), OnClose(), OnError() events) + your custom needs regarding your specific WebSocket service (e.g.: write custom properties, events and logic, for example get and store GPS positons per connected client)

-you could make not just one but several custom inherited classes from WebSocketBehavior (and add it to WebSocket server services: _webSocketServer.AddWebSocketService(..)): making several WebSocket Services on one single port. This is why you need unique strings in adding service: _webSocketServer.AddWebSocketService<WebSocketService_ServerTime>("/WebSocketService_ServerTime");

Have a nice day,
P.

Black-Byte
Posts: 17
Joined: Fri Jan 29, 2016 2:05 am

Re: WebSocket Extension for CSHTML5

Postby Black-Byte » Wed Nov 02, 2016 3:33 am

I know. We have different projects and both ways are interesting. For the first one a single webservice would be easy cause we allready use something like an webservice (websync from Frozenmountain) with an overlaying protocoll. That could i switch to a normal websocket (or the guys at Frozenmountain build a extension for cxaml, they have allready javascript/c# clients so i have started a feature request).
And with the help with c#/xaml i could rebuild the old silverlight client. I'm only waiting for some free time

Bye
Marco

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: WebSocket Extension for CSHTML5

Postby JS-Support @Userware » Thu May 18, 2017 9:00 am

The code in the first post has just been updated with the following improvements:

  • Added "ReadyState" property and enum (thank you Sesztak)
  • Fixed the error "Cannot read property 'toString' of undefined" when it was unable to connect to the server or when the returned "data" object was undefined


Return to “Extensions and Plugins for CSHTML5”

Who is online

Users browsing this forum: No registered users and 4 guests

 

 

cron