Skip to content

Example Echo

Igal edited this page May 28, 2017 · 17 revisions

This example is a simple Echo server, which accepts messages from client connections, and returns them with some arbitrary message.

First, create the Listener Component and implement the onMessage() event handler:

/** EchoListener.cfc */
component {

    function onMessage(websocket, message, sessionScope, applicationScope){

        var reply = "Echo from Lucee #Server.lucee.version# [#arguments.message#]";
        reply &= " received from #arguments.sessionScope.cfid# @ #getTickCount()#";
        return reply;
    }
}

Note that inside onMessage() you can send messages via the websocket argument, e.g. arguments.websocket.sendText(message) but, for convenience, simply returning a String value will send that message on your behalf.

Now all you have to do is register that listener with an endpoint, e.g.

<cfscript>
    endpoint = "/ws/echo";
    listener = new EchoListener();
    WebsocketRegister(endpoint, listener);
</cfscript>

Below is a complete example page which you can save as index.cfm (or whatever) and test out with the EchoListener.cfc above. Please note that the only required parts are above this paragraph, and the rest is mostly JavaScript and some basic HTML.

<!-- index.cfm !-->
<h1>WebSocket Echo Example</h1>

<cfscript>
    endpoint = "/ws/echo";
    listener = new EchoListener();
    WebsocketRegister(endpoint, listener);
</cfscript>

<p class="mt2m">Sever side code:
<p>
<code class="block"><cfset echo(htmlCodeFormat('
    <cfscript>
        endpoint = "/ws/echo";
        listener = new EchoListener();
        WebsocketRegister(endpoint, listener);
    </cfscript>
'))></code>

<cfsavecontent variable="js">
    <script type="text/javascript">
        var endpoint = "<cfset echo(endpoint)>";
        var protocol = (document.location.protocol == "https:") ? "wss://" : "ws://";
        var url = protocol + document.location.host + endpoint;

        var wsecho = new WebSocket(url);

        var log = function(evt){ console.log(evt); }
        wsecho.onopen    = log;
        wsecho.onmessage = log;
        wsecho.onerror   = log;
        wsecho.onclose   = log;
    </script>
</cfsavecontent>

<cfset echo(js)>

<p class="mt2m">Below is the JavaScript code that was used to set up the <code>wsecho</code> client:
<code class="block"><cfset echo(htmlCodeFormat(js))></code>

<p class="mt2m">Open Developer Tools and send a test message using the <code>wsecho</code>
  object, e.g.
<p>
<code class="block">
wsecho.send("Hello Lucee WebSockets at " + (new Date()).getTime());
</code>

<style>
    code   { background-color: #f0f0f0; white-space: pre-wrap; }
    .block { display: block; }
    .mt2m { margin-top: 2em; }
</style>

Watch Getting Started Video Tutorial at:

Getting Started with Lucee WebSockets

Clone this wiki locally