by Unknown user
Websockets are connections between a client and a webserver. The client can create a regular request to a webserver (an HTTP GET) and request to upgrade the connection to a bidirectional TCP connection. That connection will then remain open for as long as you want.
...
It's important to understand that a websocket connection can only be initiated by the client using a normal GET request. All major browsers support websockets websockets (http://caniuse.com/#search=websockets) - opening a websockets is done by just three lines of JavaScript. After a websocket connection is open, both sides can send messages whenever they want.
NetTalk webserver can be extended to support websockets. In this article I'll show you exactly how that's done.
Amsterdam Taxi service
I'll start with a demo to illustrate some of the possibilities of websockets. Imagine that you're running a taxi service in the center of Amsterdam. All taxis are equipped with a GPS enabled smart phone. Using websockets, those devices can send their location every second without overloading the webserver because the websocket protocol hardly has any overhead.
...
The fluency of this interface can only be achieved by websockets. It goes without saying that when taxis move around through the city, having the positions update as often as possible is a must have.
So, how does it work?
The taxi app is a regular NetTalk webserver application, extended with websocket capabilities. Below I'll explain extactly how the taxi application uses those websockets.
IndexPage
The indexPage contains code to allow a connection to be upgraded to a websocket. To initiate a websocket, a browser will send a normal GET request with some extra HTTP headers. If those headers are present, the IndexPage will upgrade the connection with the webserver to a websocket by calling the Add() method of the global WebSocketServerClass.
CityMap procedure
The CityMap source procedure will load a bit of HTML from disk that contains the map image, a canvas which is rendered on top of the map and a draggable image of a taxi. This procedure also contains a bit of JavaScript that will initialize the JavaScript class that will handle the websocket.
...
CSS is used to position the canvas and the taxi image on top of the image with the map of Amsterdam. In cases like this where positioning the elements is critical, I find it easier to write the HTML in an editor and include the contents in NetTalk's response by using the LoadFile method of the packet class:
...
Note |
---|
The browser will not receive any data or html automatically. You will have to explicitly send data to the connected client(s). You can easily send data to a newly connected client by embedding code in the WebsocketsHandler as explained later in this article. |
DispatchForm procedure
The DispatchForm procedure contains the form to add a new ride. This form is not linked to a table and does not have a regular save button.The 'Save ride' button instead is a button with only a single line of JavaScript attached to the onclick event.
...
The local PersonCount field on this form needs to have server-side validation. The validation will trigger an Ajax request making sure that the server knows how many people are waiting for a ride. We'll see in a bit when this comes into play.
Client side code
The IndexPage also contains two JavaScript files.
...
This class only handles the message events. event.data contains the actual message sent by the server. In this particular application, all messages are in JSON format which is why the message is parsed to a JSON structure. The message doesn't have to be in JSON format though, you can just as easily send semi-colon separated strings or whatever else suits you best.
WebSocketsHandler
The WebSocketsHandler procedure is the websocket equivalent of NetTalk's Webhandler. It will be called for every websocket request and can run simultaneously on multiple threads.
...
All these methods are threadsafe
TaxiMapClass
The TaxiMapClass is a global class that wraps two queues and contains the code to send messages to all taxis. One queue contains all taxis, the other queue contains the rides.
...
This method will be called for each message that any client sends. In this demo, all messages are sent in JSON format. If the MsgType property of the message contains the text 'POSITIONUPDATE, a taxi has been moved on the map. Using the socketID, we'll get the taxi from the queue and update its position. The new position is then wrapped in a new JSON string which will be broadcast to all connected clients. Every connected client - regardless of whether they have signed in as a taxi - will receive this positionUpdate. New rides however, will only be sent to taxis.
Introducing the websocket templates!
The websocketserver class can easily be added to any NetTalk webserver application by adding the websocket extension template. Since it depends on NetTalk webserver, please make sure you have highlighted the webserver extension template before attempting to add the websocket extension template.
...
Your NetTalk webserver is now websocket aware. It doesn't do anything useful though. It just accepts websocket requests and will receive all messages that the attached clients send.
A basic implementation of websockets
Just embed code into the WebsocketRequestHandler procedure to start leveraging this awesome functionality. Let's do something pretty basic: broadcast all messages to all clients:
...
Almost every line has a comment explaining what it does, so the code should speak for itself. This code will generate the following JavaScript:
Code Block | ||
---|---|---|
| ||
<script type="text/JavaScript"> |
...
function handleMsg(eventType, msg) { |
...
if(eventType == DDSocketApp.MessageEvent) { |
...
$('#LOC__Received').val( $('#LOC__Received').val() + msg.data + '\r\n');} |
...
} |
...
var ws = new DDSocketApp.SocketBase('ws://127.0.0.1:89/WSDemoPage', handleMsg ); |
...
if(!ws.supported()) { |
...
alert('Sockets are not supported.') |
...
} |
...
else { |
...
ws.connect(); |
...
} |
And that completes the app. It should look like this:
As soon as you open this url in a second browser, this browser window will be immediately notified that a new client has connected. All messages that you send from either window, will appear in both windows. And there you have it, a very simple websocket application!
Want to see more?
This taxi demo and several other demo applications demonstrating some of the use cases for websockets (such as a concurrency checker with an online chatting option, the taxi demo and a shopping cart with online help) are available for download:
...
I would also like to encourage you to view ClarionLive session #291 that discusses all the demos.
Please note that the download does not contain the websocket classes nor the websocket templates and that you will therefore not be able to compile the demos. The compiled versions of the demos are included, so you will be able to run the demos on your machine.
How to obtain the websockets classes
The websocket classes require NetTalk 8, StringTheory and Cryptonite.
...