registerWebSocketServer

Top  Previous  Next

This function registers a websocket server on the webserver. Websockets are a way for 2 way communication from the webserver to the browser. This allows the webpage to be dynamically updated without having to poll the webserver for changes. This is because the webserver can now initiate a transfer to the browser.

 

This websocket implementation supports two different websocket wireformats:

 

http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76

http://tools.ietf.org/html/rfc6455

 

This should cover most of the browsers on the market today.

Definition

webserver.registerWebSocketServer(hostname, path, websocketFactory)

 

 

Name

Type

Description

hostname

string

The name of the host this websocket should listen on or "*" for all hosts.

path

string

The path of the websocket on the server starting with a slash. For example "/test"

websocketFactory

function

Function that is called when a websocket is requested. This function is passed the websocket communication object. This function must return a websocket lua object.

 

 

Websocket Lua Object

Return value

Signature

Description

string

accept( self, secure, url, headers, peerAddress, peerPort )

This function is called when a new websocket is requested. Note that you must return the protocol this socket speaks if you accept the connection or nil to reject

 

connected()

This function is called when the browser also accepts the connection and the connection is ready for data.

 

disconnected()

This function is called when the websocket connection was closed.

 

received( string )

This function is called when data comes in.

Websocket Communication Object

Return value

Signature

Description


sendText ( string )

sends the string to the remote end


close()

closes the connection

Example

This code should be run when Girder starts ( or after a lua reset. ). You can place it in an action with the appropriate events attached. If all is well you should see "websocket registered" in the lua console.

ExampleWebSocket = require("examples.websocket")

 

print(webserver.registerWebSocketServer("*", "/test", function( ws )

    print("starting!")

    

    exampleWebSocket = ExampleWebSocket.new(ws)

    return exampleWebSocket

    

end))

 

print("websocket registered")

 

The examples/websocket.lua file contains this:

 

local base = require('Class')

local timer = require('timer')

 

local print = print

 

module(...)

 

base:subclass( _M)

 

function accept ( self, secure, url, headers, host, port )

 print(secure, url)

 return true, "test" -- you must return a matching protocol here!

end

 

function onTimeout(self)

 self.ws:sendText("Ping")

end

 

function connected(self)

 print("Websocket connected")

 self.timer = timer.new(1000, function() 

         onTimeout(self)

 end)

 self.timer:start();

end

 

function disconnected(self)

 print("Websocket disconnected")

 if self.timer then

         self.timer:stop()

         self.timer:deinit()

         self.timer = nil

 end

end

 

function received(self, text)

 print("Received: ", text)

 self.ws:sendText("You sent me: " .. text)

end

 

function deinit(self)

 self.ws = nil

end

 

function init ( self, ws )        

 base.init(self)

 self.ws = ws

end

 

The HTML file that goes with this looks like this:

 

<html>

<head>

 <title>

 Chat demo

 </title>

<style type="text/css">

body {

 background-color: #a0a0a0;

 background-image: url(Girder3D-436.png);

}

 

#connectedDiv {

 display:none;

}

 

#frame {

 width:800px;

 background-color:white;

 border: 3px solid black;

 padding: 20px;

 

}

 

</style>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>    

<script type="text/javascript">

 

 var chatName = "";

 var timer = 0;

 var status;

 var txt;

 var line;

 var broadcastSocket;

 var secure = "wss://<% print(getHost() .. ":" .. getPort()) %>/test";

 var plain = "ws://<% print(getHost() .. ":" .. getPort()) %>/test";

 var useSecure = false

 

 function startChat(url) {

         

                         

         broadcastSocket = new WebSocket(url, "test");

         

         broadcastSocket.onopen = function (event) {

                 $("#status").text( "Status: connected");        

                 broadcastSocket.send($("#nameEdit").val() + " has joined.");

         };        

         broadcastSocket.onclose = function (event) {          

                 $("#status").text( "Status: disconnected");

                 setTimeout( function () {

                         $("#status").text( "Status: connecting...");

                         startChat( useSecure ? secure : plain );

                 }, 5000);

         };        

         broadcastSocket.onmessage = function(event) {

                 $("#status").text( "Status: connected");

                 $("#text").text( $("#text").text() + "\n" + event.data);                        

         };        

 

 

 

 }

 

 $(document).ready( function () {

 

         status = $("#status");

         txt = $("#text");

         line = $("#line");

 

         $("#nameSubmitPlain").click( function () {

 

                 if ( $("#nameEdit").val() === "" ) {

                         alert("Please enter a name");

                         return;

                 }

                 chatName = $("#nameEdit").val();

                 useSecure = false;

                 startChat( useSecure ? secure : plain );

                 

                 $("#connectedDiv").show();

                 $("#nameDiv").hide();

 

         });

 

         $("#nameSubmitSecure").click( function () {

 

                 if ( $("#nameEdit").val() === "" ) {

                         alert("Please enter a name");

                         return;

                 }

                 chatName = $("#nameEdit").val();

                 useSecure = true;

                 startChat( useSecure ? secure : plain );

                 

                 $("#connectedDiv").show();

                 $("#nameDiv").hide();

 

         });

 

         

         $("#sendButton").click( function () {

                 broadcastSocket.send( chatName + " | " + line.val() );

                 line.val("");

         });        

         

 });

 

</script>

 

</head>

<body>

 

<center>

<div id="frame">

<h1>Chat Demo</h1>

 

<div id="nameDiv">

Please enter your name

<input type="text" id="nameEdit"><button id="nameSubmitPlain">Connect Plain</button>

<button id="nameSubmitSecure">Connect Secure</button>

</div>

 

<div id="connectedDiv">

 

<p id="status">Status: Unknown<p>

<textarea id="text" cols="80" rows="20"></textarea><br>

<input type="text" id="line"> <button id="sendButton">Send</button>

</div>

</div>

<center>

 

</body>

</html>

 

 

The file above is available "wsexample.lhtml" after making sure the websocket lua code was loaded hit http://localhost/wsexample.lhtml. This then should print "Websocket connected" on the lua console. Now you can send text to the browser with exampleWebSocket.ws:SendText("Hello")