Source language: Translate to:

websockets javascript

General questions about NeoAppBuilder - our rapid application development tool for building HTML5, web and mobile apps.

Moderator: Neosoft Support

websockets javascript

Postby TinTin » Tue Mar 24, 2015 1:53 pm

Hi there,

I'm sure this is now possible, I'm using NSBasic App Studio and may well port across at some point...

I'm assuming it's easy to grab variables from websocket.js

Can you assign a subroutuine for each event?

Any help would be appreciated.

AJ

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
TinTin
 
Posts: 162
Joined: Sun Dec 06, 2009 4:03 am
Location: UK

Re: websockets javascript

Postby TinTin » Thu Mar 26, 2015 10:14 am

I made a start, im not great with Javascript but think I'm heading in the right direction, I have created 4 subroutines for each event,
I'm assuming if I wan't to replicate a 'send' webcokset message I can by using JS block as

BeginJS
websocket.send("Test To Send")
EndJs



BeginJS
var websocket = document.createElement('websocket')
websocket = new window.WebSocket("ws://127.0.0.1:8190")
websocket.onopen = $scope.wsOpenSub();
websocket.onclose = $scope.wsCloseSub();
websocket.onmessage = $scope.wsMessageSub();
websocket.onerror = $scope.wsErrorSub();
EndJS

If websocket support is able to work inside NAB it opens up great interapp communication with existing NB apps.!!
TinTin
 
Posts: 162
Joined: Sun Dec 06, 2009 4:03 am
Location: UK

Re: websockets javascript

Postby Neosoft Support » Thu Mar 26, 2015 4:37 pm

I don't really have much experience with websockets, but this sounds very interesting. It could be useful for many types of applications.
NeoSoft Support
Neosoft Support
NeoSoft Team
 
Posts: 5593
Joined: Thu Mar 31, 2005 10:48 pm
Location: Oregon, USA

Re: websockets javascript

Postby Gaev » Thu Mar 26, 2015 7:39 pm

TinTin:

This code (defined for click event of a PushButton) works as advertised ...
Code: Select all
BeginJS

//websocket
wsLog = "WEBSOCKET LOG";
wsUri = "wss://echo.websocket.org/";
wsSendText = "WebSocket rocks";

function testWebSocket()
{
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
}

function wsLogMessage(logText){
   wsLog = wsLog + "\n" + logText;
}

function doSend(message){
    wsLogMessage("ABOUT TO SEND: " + message);
    websocket.send(message);
}

function onMessage(evt){
    wsLogMessage("RESPONSE: " + evt.data);
    websocket.close();
}


function onOpen(evt){
    wsLogMessage("CONNECTED");
    doSend(wsSendText);
}

function onClose(evt){
    wsLogMessage("DISCONNECTED");
    alert(wsLog);
}

function onError(evt){
    wsLogMessage("ERROR: " + evt.data);
    alert(wsLog);
}

testWebSocket();
EndJS


Note: It was composed from example at https://www.websocket.org/echo.html

I ran this in Firefox ... even though Firefox supports WebSocket, it did not respond to the non-secure (ws: protocol) ... so I used the secure (wss:) protocol.
User avatar
Gaev
 
Posts: 3718
Joined: Fri Apr 01, 2005 7:48 am
Location: Toronto, Canada

Re: websockets javascript

Postby David de Argentina » Sat Mar 28, 2015 8:59 am

Very very very interesting sample.

I'm trying to get the server-side files in use.

I got this .js :

Save as echo.js

Syntax: [ Download ] [ Hide ]
Using Javascript Syntax Highlighting
  var secureCb;
  var secureCbLabel;
  var wsUri;
  var consoleLog;
  var connectBut;
  var disconnectBut;
  var sendMessage;
  var sendBut;
  var clearLogBut;

  function echoHandlePageLoad()
  {
    if (window.WebSocket)
    {
      document.getElementById("webSocketSupp").style.display = "block";
    }
    else
    {
      document.getElementById("noWebSocketSupp").style.display = "block";
    }

    secureCb = document.getElementById("secureCb");
    secureCb.checked = false;
    secureCb.onclick = toggleTls;
   
    secureCbLabel = document.getElementById("secureCbLabel")
   
    wsUri = document.getElementById("wsUri");
    toggleTls();
   
    connectBut = document.getElementById("connect");
    connectBut.onclick = doConnect;
   
    disconnectBut = document.getElementById("disconnect");
    disconnectBut.onclick = doDisconnect;
   
    sendMessage = document.getElementById("sendMessage");

    sendBut = document.getElementById("send");
    sendBut.onclick = doSend;

    consoleLog = document.getElementById("consoleLog");

    clearLogBut = document.getElementById("clearLogBut");
    clearLogBut.onclick = clearLog;

    setGuiConnected(false);

    document.getElementById("disconnect").onclick = doDisconnect;
    document.getElementById("send").onclick = doSend;

  }

  function toggleTls()
  {
    var wsPort = (window.location.port.toString() === "" ? "" : ":"+window.location.port)
    if (wsUri.value === "") {
        wsUri.value = "ws://" + window.location.hostname.replace("www", "echo") + wsPort;
    }
   
    if (secureCb.checked)
    {
      wsUri.value = wsUri.value.replace("ws:", "wss:");
    }
    else
    {
      wsUri.value = wsUri.value.replace ("wss:", "ws:");
    }
  }
 
  function doConnect()
  {
    if (window.MozWebSocket)
    {
        logToConsole('<span style="color: red;"><strong>Info:</strong> This browser supports WebSocket using the MozWebSocket constructor</span>');
        window.WebSocket = window.MozWebSocket;
    }
    else if (!window.WebSocket)
    {
        logToConsole('<span style="color: red;"><strong>Error:</strong> This browser does not have support for WebSocket</span>');
        return;
    }

    // prefer text messages
    var uri = wsUri.value;
    if (uri.indexOf("?") == -1) {
        uri += "?encoding=text";
    } else {
        uri += "&encoding=text";
    }
    websocket = new WebSocket(uri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
  }
 
  function doDisconnect()
  {
    websocket.close()
  }
 
  function doSend()
  {
    logToConsole("SENT: " + sendMessage.value);
    websocket.send(sendMessage.value);
  }

  function logToConsole(message)
  {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = getSecureTag()+message;
    consoleLog.appendChild(pre);

    while (consoleLog.childNodes.length > 50)
    {
      consoleLog.removeChild(consoleLog.firstChild);
    }
   
    consoleLog.scrollTop = consoleLog.scrollHeight;
  }
 
  function onOpen(evt)
  {
    logToConsole("CONNECTED");
    setGuiConnected(true);
  }
 
  function onClose(evt)
  {
    logToConsole("DISCONNECTED");
    setGuiConnected(false);
  }
 
  function onMessage(evt)
  {
    logToConsole('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
  }

  function onError(evt)
  {
    logToConsole('<span style="color: red;">ERROR:</span> ' + evt.data);
  }
 
  function setGuiConnected(isConnected)
  {
    wsUri.disabled = isConnected;
    connectBut.disabled = isConnected;
    disconnectBut.disabled = !isConnected;
    sendMessage.disabled = !isConnected;
    sendBut.disabled = !isConnected;
    secureCb.disabled = isConnected;
    var labelColor = "black";
    if (isConnected)
    {
      labelColor = "#999999";
    }
     secureCbLabel.style.color = labelColor;
   
  }
       
        function clearLog()
        {
                while (consoleLog.childNodes.length > 0)
                {
                        consoleLog.removeChild(consoleLog.lastChild);
                }
        }
       
        function getSecureTag()
        {
                if (secureCb.checked)
                {
                        return '<img src="img/tls-lock.png" width="6px" height="9px"> ';
                }
                else
                {
                        return '';
                }
        }
 
  window.addEventListener("load", echoHandlePageLoad, false);
 
Parsed in 0.021 seconds, using GeSHi 1.0.8.10


Save as stuff.js:

Syntax: [ Download ] [ Hide ]
Using Javascript Syntax Highlighting
var BrowserDetect = {
        init: function () {
                this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
                this.version = this.searchVersion(navigator.userAgent)
                        || this.searchVersion(navigator.appVersion)
                        || "an unknown version";
                this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
                for (var i=0;i<data.length;i++) {
                        var dataString = data[i].string;
                        var dataProp = data[i].prop;
                        this.versionSearchString = data[i].versionSearch || data[i].identity;
                        if (dataString) {
                                if (dataString.indexOf(data[i].subString) != -1)
                                        return data[i].identity;
                        }
                        else if (dataProp)
                                return data[i].identity;
                }
        },
        searchVersion: function (dataString) {
                var index = dataString.indexOf(this.versionSearchString);
                if (index == -1) return;
                return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
                {
                        string: navigator.userAgent,
                        subString: "Chrome",
                        identity: "Chrome"
                },
                {       string: navigator.userAgent,
                        subString: "OmniWeb",
                        versionSearch: "OmniWeb/",
                        identity: "OmniWeb"
                },
                {
                        string: navigator.vendor,
                        subString: "Apple",
                        identity: "Safari",
                        versionSearch: "Version"
                },
                {
                        prop: window.opera,
                        identity: "Opera"
                },
                {
                        string: navigator.vendor,
                        subString: "iCab",
                        identity: "iCab"
                },
                {
                        string: navigator.vendor,
                        subString: "KDE",
                        identity: "Konqueror"
                },
                {
                        string: navigator.userAgent,
                        subString: "Firefox",
                        identity: "Firefox"
                },
                {
                        string: navigator.vendor,
                        subString: "Camino",
                        identity: "Camino"
                },
                {               // for newer Netscapes (6+)
                        string: navigator.userAgent,
                        subString: "Netscape",
                        identity: "Netscape"
                },
                {
                        string: navigator.userAgent,
                        subString: "MSIE",
                        identity: "Explorer",
                        versionSearch: "MSIE"
                },
                {
                        string: navigator.userAgent,
                        subString: "Gecko",
                        identity: "Mozilla",
                        versionSearch: "rv"
                },
                {               // for older Netscapes (4-)
                        string: navigator.userAgent,
                        subString: "Mozilla",
                        identity: "Netscape",
                        versionSearch: "Mozilla"
                }
        ],
        dataOS : [
                {
                        string: navigator.platform,
                        subString: "Win",
                        identity: "Windows"
                },
                {
                        string: navigator.platform,
                        subString: "Mac",
                        identity: "Mac"
                },
                {
                           string: navigator.userAgent,
                           subString: "iPhone",
                           identity: "iPhone/iPod"
            },
                {
                        string: navigator.platform,
                        subString: "Linux",
                        identity: "Linux"
                }
        ]

};
BrowserDetect.init();
Parsed in 0.014 seconds, using GeSHi 1.0.8.10


But i can't determine what kind of file get the .onMessage function at server-side

If any can isolate the another server files, could put them at this post ?

Thanks in advance,
David de Argentina
User avatar
David de Argentina
 
Posts: 1553
Joined: Mon Apr 04, 2005 4:13 pm
Location: Buenos Aires, Argentina

Re: websockets javascript

Postby Gaev » Sat Mar 28, 2015 10:20 am

David de Argentina:

But i can't determine what kind of file get the .onMessage function at server-side


1) What kind of script (php, node/javascript, .net, java, ruby, python, perl etc.) will you be running on your server ?

2) This page https://developer.mozilla.org/en-US/docs/WebSockets has some documentation ... including https://developer.mozilla.org/en-US/doc ... et_servers ... and some examples (frameworks) for use with node.js

3) Another useful article is at http://www.html5rocks.com/en/tutorials/ ... serverside

4) You can also do a Google Search for "websocket server" ... and look at results including ...

http://www.codeproject.com/Articles/570 ... ket-Server
https://developer.mbed.org/cookbook/Websockets-Server

... or a more specific search like "websocket server php".

As mentioned in my previous post ... use wss: instead of ws: in your URI when testing your App from NeoAppBuilder ... Browsers (like Firefox) will simply ignore your message (to ws: sites) because it considers your App to be non-secure ... of course, this requires your server to be able to support secure communications.
User avatar
Gaev
 
Posts: 3718
Joined: Fri Apr 01, 2005 7:48 am
Location: Toronto, Canada

Re: websockets javascript

Postby David de Argentina » Sat Mar 28, 2015 10:26 am

Thanks Gaev,

I found this one:

http://www.sanwebe.com/2013/05/chat-usi ... php-socket

I think there are all we need to put in work the sample

Greetings from Buenos Aires,

David de Argentina
User avatar
David de Argentina
 
Posts: 1553
Joined: Mon Apr 04, 2005 4:13 pm
Location: Buenos Aires, Argentina

Re: websockets javascript

Postby TinTin » Sun Mar 29, 2015 10:04 am

Sorry all wasn't being rude some very useful and helpful replies for some reason my forum notification emails weren't coming though so had no idea everyone had jumped on.. Some late weekend testing for me now.

Thanks all, much appreciated.
TinTin
 
Posts: 162
Joined: Sun Dec 06, 2009 4:03 am
Location: UK


Return to General NeoAppBuilder Discussion

Who is online

Users browsing this forum: No registered users and 0 guests

cron