Writing A Daytime Server In Node.js

I’ve previously written about using node.js as a simple UDP listener, now I thought I’d expand on this and give an example of a node.js application that works as both a UDP and TCP server.

A simple service that offers both UDP and TCP connections would be the Daytime Protocol, as defined in RFC 867. It listens to port 13 for both TCP and UDP connections, and returns the current date and time. Your local computer may well have this function enabled, to test the TCP version, you can simply telnet to port 13 and see what is returned.

telnet localhost 13

If you find you don’t have a local Daytime service running, try calling the one at time.ien.it, you should see something like this…

$ telnet time.ien.it 13
Trying 193.204.114.105...
Connected to ntp.ien.it.
Escape character is '^]'.
12 APR 2011 18:51:11 CEST
Connection closed by foreign host.

As you can see it simply returns the date and time before closing the connection.

We could write something like this very easily in node.js. In this case we’ll return the date in JavaScript’s UTC string format instead to keep it simple.

var net = require('net');
var port = 1300;
var now = function() {
  var date = new Date();
  return new Buffer(date.toUTCString() + "rn");
};
var tcpserver = net.createServer(function(c) {
  c.write(now());
  c.end();
});
tcpserver.listen(port);

We can test this by telneting to localhost on port 13

$ telnet localhost 1300
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Tue, 12 Apr 2011 17:17:55 GMT
Connection closed by foreign host.

Let’s take a quick detour into what the code is doing if you’ve not used node.js for any network programming before.

We require('net') so we can use node.js’s network socket support.

The now() function simply returns a Buffer with the current UTC date and time string in. A Buffer in node.js refers to the raw memory used behind the data, in this case our string with the date and time in.

Finally, we create the server, and add a callback function that is called when something connects to the socket. In this case we’re just writing out the contents of the now() function and ending the connection. Last but not least, we tell the socket which port to listen on.

We can see that this code works, but the Daytime protocol also offers a UDP service on the same port that can return the date and time string to a client.

Let’s add in some code to support this. We’ll assume our now() function and port variable are available already.

var dgram = require('dgram');
var udpserver = dgram.createSocket("udp4", function(msg, rinfo) {
  var daytime = now();
  udpserver.send(daytime, 0, daytime.length, rinfo.port, rinfo.address);
});
udpserver.bind(port);

So what is going on here? Well like the TCP code, we have to require('dgram'); to have access to node.js’s UDP support.

Next we create the socket and create a callback function that returns the date and time string back to the IP address and port of the calling computer. Finally we bind this to the port so we start listening for messages.

It’s harder to test a UDP server as we can’t telnet in, we will have to write a simple UDP client to send a blank message to the server and print out any replies to the console.

var dgram = require('dgram');
var message = new Buffer(" ");
var server_ip = '127.0.0.1';
var server_port = 43278;
var client = dgram.createSocket("udp4");
client.on('message', function (msg) {
  console.log(msg.toString());
  client.close();
});
client.send(message, 0, message.length, server_port, server_ip);

When you run this client on the same machine as your server you should get back the current date and time.

Here’s the final code for our Daytime server.

var net = require('net');
var dgram = require('dgram');
var port = 1300;
var now = function() {
  var date = new Date();
  return new Buffer(date.toUTCString() + "rn");
}
var tcpserver = net.createServer(function(c) {
  c.write(now());
  c.end();
});
tcpserver.listen(port);
var udpserver = dgram.createSocket("udp4", function(msg, rinfo) {
  var daytime = now();
  udpserver.send(daytime, 0, daytime.length, rinfo.port, rinfo.address);
});
udpserver.bind(port);

Writing A UDP Server Using Node.js

Previously, I’ve written about using node.js to send a heartbeat to a python server using a UDP datagram.

Of course you may not want to run Python if you using node.js so I thought I’d give you a quick run through on writing a UDP server using node.js.

The earlier heartbeat example sent a small message saying “PyHB” to a server listening on port 43278. This example will listen out for that message and show it on the console to prove it’s working.

The first thing we need to do is to require("dgram") to allow us access to the dgram library.

var dgram = require("dgram");

We now need to create a datagram socket to listen on, as we’re going to listen out for an IP4 datagram we create this of type udp4.

var server = dgram.createSocket("udp4");

Node.js lets us bind to events, and dgram gives us three, message, listening and close.

To listen for an event, we need to use the listening event. As with other JavaScript events, we can pass in a callback function to actually do something when the event is fired. In this case, we’ll just use display the incoming message on the console, along with some details of the server that sent it.

server.on("message", function (msg, rinfo) {
  console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});

It’s also useful to know we’ve actually setup our socket correctly, so we can use the listening event to return a message to console that everything has been setup OK and is working.

server.on("listening", function () {
  var address = server.address();
  console.log("server listening " + address.address + ":" + address.port);
});

Finally we need to actually bind our socket to a port so it can start listening for messages. For this we have to use the bind method.

server.bind(43278);

Putting this all together we have the following code that can listen for UDP datagrams and show them on the console.

var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
  console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});
server.on("listening", function () {
  var address = server.address();
  console.log("server listening " + address.address + ":" + address.port);
});
server.bind(43278);

I hope this has been a useful quick introduction to writing a UDP server in node.js.

Using Node.js To Send A Heartbeat To A Python Server

I’ve been looking back at some old code and I found an old piece on using Perl to send a heartbeat to a Python server.

Recently I’ve been using the excellent node.js to do some cool JavaScript on the server side instead of in a client on a web broswer. I thought it would be fun to covert this simple script over to JavaScript.

This example is based on recipe 13.11 in the Python Cookbook.

The script needs to send a UDP datagram to a server listening on port 43278. In this example the server will be listening on localhost, 127.0.0.1.

As with the Perl script, we’ll set a few “constants” to let us change things easily if we want to. As JavaScript doesn’t have constants in this example we’ll just use variables. Firstly we nee to require “dgram” so we can use UDP datagrams. We’ll set the server ip address, the port to use, the time in seconds to send the heartbeat, a debug flag if we want to see a message on the console everytime we send a message, and the message itself “PyHB”.

var dgram = require('dgram');
var message = new Buffer("PyHB");
var server_ip = '127.0.0.1';
var server_port = 43278;
var beat_period = 5;
var debug = 1;

We’ll need to send out our heartbeat every beat_period seconds. To do this we can use JavaScript’s setInterval function to execute code every X milliseconds. As we’ve defined our beat_period in seconds, we’ll need to mulitply this value by 1000 to get the time in milliseconds.

setInterval(function() {
// datagram code goes here.
}, beat_period * 1000);

The code to send the datagram is really simple, 3 lines infact. We create a client socket, send the message then close the client socket.

var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, server_port, server_ip);
client.close();

Putting this together, along with a bit of debugging information, we get the following code.

var dgram = require('dgram');
var message = new Buffer("PyHB");
var server_ip = '127.0.0.1';
var server_port = 43278;
var beat_period = 5;
var debug = 1;
console.log("Sending heartbeat to IP " + server_ip + " , port " + server_port);
console.log("press Ctrl-C to stop");
setInterval(function() {
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, server_port, server_ip);
client.close();
if (debug)
console.log("Time: " + new Date());
}, beat_period * 1000);

I hope that was a useful introduction to sending messages using UDP in Node.js.

Creating A New Element With jQuery, With Or Without A Plugin

UPDATE: Whilst this remains an interesting example of creating a simple plugin, I no longer recommend this way of creating elements in jQuery. Instead just pass the html you want to use into jQuery directly as a string, e.g. var myH1Element = jQuery("<h1>My H1 Test</h1>");.

One function that seems to be missing in jQuery is to create new elements outside of the current DOM.

There is a good reason for this, normal vanilla JavaScript has the function createElement to do the job for you.

To create a new h1 element for example, we can do the following.

var myH1Element = document.createElement('h1');

We can easily combine this with jQuery to set the text inside for example…

jQuery(myH1Element).text("My H1 Text");

There is one downside, using the standard createElement we’re not able to chain functions with jQuery.

The way around this is to wrap the request in jQuery like this…

jQuery(document.createElement("h1"));

Now we can chain this together as before…

jQuery(document.createElement("h1")).text("My H1 Text");

If you don’t like the look of that, then we could always create a jQuery plugin, and add a createElement function to jQuery.

jQuery.extend({
createElement : function(elementName) {
return jQuery(document.createElement(elementName));
}
});

That must be one of the simpliest jQuery plugins ever!

Now we have extended jQuery with a createElement function we can chain calls to it like this.

jQuery.createElement("h1").text("My H1 Text").appendTo("body");

This will create a new h1 element, add the text “My H1 Text” inside the h1, then append the h1 inside the documents body tag.

Using jQuery And Mootools On The Same Page

While it’s never a good idea to bloat your webpage with too much unneeded content, there are times when you can’t avoid it. One example I came across recently was with my day job’s adoption of jQuery as our official JavaScript framework, I needed to add some jQuery goodness to some blog pages belonging to a certain category in Movable Type. Simple, right?

Well the site in question already used Mootools extensively, so the jQuery would have to run nicely next Mootools and not disrupt existing functionality.

The designers of jQuery have designed for this sort of situation, and have provided a function called noConflict that returns the use of $ to Mootools, or any other framework you may have installed as well.

Here’s some example code to show both jQuery and Mootools running in the same page…

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

In my Movable Type situation, I am able to use a custom MT tag to make sure jQuery only appears for certain categories. Let’s assume I have a category called jQuery where I need the jQuery library to be imported, the MTIfCategory tag is what I need to guard with…

<MTIfCategory label="jQuery">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
</MTIfCategory>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

With this in place I can call jQuery functions using the jQuery variable, and MooTools using $ where necessary.

Writing A jQuery Plugin To Stripe A Table

One of the most powerful features of jQuery is it’s plugin architecture. This allows developers to easily extend jQuery’s functionality.

I’ve decided to extend my table striping example code and turn it into a jQuery plugin. If I have a table with an id of test, I want to be able to call a stripe function on it’s selector, e.g. $('#test').stripe();

So how do we build this? Well firstly, as it’s a plugin we shouldn’t really be playing with the $ jQuery object incase our user has disabled it. There is a trick to get around this though…

(function($){
// code here can safely use $
})(jQuery);

What’s happening here? Well we’re using a closure to create an anonymous function into which we pass in the jQuery object. The parameter name we use in this function is $ so we can use this inside safely, even if the user has disabled this variable outside our plugin.
Now we have our $ variable we can get on with building the plugin.

$.fn.stripe = function(options) {
// define our function action here.
}

Here we’ve added a function to jQuery called stripe and told it to reference a fuction we’ve defined. Now we need to add the magic to this function to actually do the striping.

return this.each(function() {
$('/tbody:first>tr:even',this).addClass('even');
$('/tbody:first>tr:odd',this).addClass('odd');
});

As a jQuery selector can run over multiple items, we need to make sure we iterate over each of these. We use jQuery’s built in each function to do this. this refers to the current selector in this case.

Inside, we need to select the first tbody element of the selection, then for each child tr depending if it’s odd or even we set the class of that tr to be either even or odd. This should ensure that nested tables won’t be striped.

That’s great, but what would be even more useful would be the ability to define different class names dynamically so we’re not stuck with the two hardcoded ones.

This is easy to achieve by creating a set of defaults in a private object, passing overrides into our function, and using jQuery’s excellent extend function to merge the two.

var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);

Now we can either just call .stripe directory, or pass in override options like this, .stripe({odd: 'testdark', even: 'testeven')

Putting this all together, we get the following code for our stripe plugin.

(function($){
$.fn.stripe = function(options) {
var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);
return this.each(function() {
$('/tbody:first>tr:even',this).addClass(options.even);
$('/tbody:first>tr:odd',this).addClass(options.odd);
});
}
})(jQuery);

A configurable jQuery plugin, in just 13 lines of JavaScript. Marvellous!

Alternating Table Rows With JavaScript And jQuery

One of the most popular stories on this website is on Alternating Table Rows With Template Toolkit And CSS. The example I use is how to stripe alternate rows in an HTML table by applying a seperate class to each row.

As I’ve been learning jQuery lately, I thought I’d update this example to show how to do it using this excellent JavaScript framework.

Firstly, we need to setup our styles. We’ll have a lite and a dark class to use that will just set a different background colour.

<style type="text/css">
.lite {background-color: #ddffff;}
.dark {background-color: #aaffff;}
</style>

We’ll also need an example table.

<table class="stripe">
<tbody>
<tr>
<td>1</td><td>One</td>
</tr>
<tr>
<td>2</td><td>Two</td>
</tr>
<tr>
<td>3</td><td>Three</td>
</tr>
<tr>
<td>4</td><td>Four</td>
</tr>
<tr>
<td>5</td><td>Five</td>
</tr>
</tbody>
</table>

Notice how I have given the table a class of stripe. This is important, I’m going to use jQuery to only select table elements that have this class name, else every table on the page would be striped.

The jQuery to achieve the striping is actually very simple.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('table.stripe>tbody>tr:even').addClass("lite");
$('table.stripe>tbody>tr:odd').addClass("dark");
});
</script>

Firstly we added the jQuery library to the page. Next we setup our striping code to only run once the DOM is place. This is important as we’re going to be selecting and manipulating over the DOM next. The next two lines apply the lite class to even table rows and the dark class to odd table rows. Let’s look at this in a bit more detail.

The selector $('table.stripe>tbody>tr:even') is easier to explain backwards. We look for even matching tr elements, that have a parent of tbody, that has a parent of table with a class of stripe. The use of the > symbol instead of just a space is to make sure the elements are direct parent and child elements instead of just ancestor and descendant. Why is this important? Well if we used a space any nested tables that happened to have an striped ancestor would also be striped. This isn’t normally what we’d want to happen.

Knowing When It’s Safe To Talk To Flash From JavaScript – Part 2

In the previous article Knowing When It’s Safe To Talk To Flash From JavaScript we saw how to call Flash from JavaScript.

We embedded the Flash movie directly into the page, however there are times when we may want to insert the movie dynamically using JavaScript. How can we do this?

Well it turns out fairly easily, especially if we use one of the modern JavaScript framework libraries like jQuery.

jQuery is very extendable, and has a powerful plugin based architecture. Thankfully someone has done the hard work for us and written a plugin to handle the embedding of Flash. Take a look at the jQuery.flash plugin.

How do we use it, well first we need to add the two libraries to the page, jQuery and jQuery.flash.

<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.flash.js"></script>

In our page body, we’ll add a bit of HTML that will have it’s content replaced by the Flash movie.

<-- the content of the following div will be replaced. -->
<div id="example">Flash here</div>

Now let’s add the JavaScript that will replace the div’s content. We’ll wrap it inside jQuery’s ready function to make sure everything we need is in place. This is a better version of the window.onload function we saw in the previous article that waits until the page can be manipulated, and not until everythting has been downloaded.


$(document).ready(function() {
$('#example').flash(
{
src: 'test.swf',
height: 1,
width: 1,
flashvars: {onLoad: 'flashLoaded'}
},
{ version: 8}
);
});

This creates the object or embed as necessary, and loads the movie “test.swf”, with a height and width of 1 pixel and the flashvars parameters we saw in the previous article. In this case, the onLoad parameter has a value of flashLoaded, the name of the function we want to call when the flash has loaded and is ready to execute. There is also a parameter saying the minimum version of the Flash player we need, let’s use version 8 here.

Now when the page is loaded, the <div> block will be replaced with the flash movie, and this in turn will call our callback function flashLoaded.

Update: Using Mootools

Mootools is another excellent JavaScript framework library, and it has Flash support built into it’s core using the Swiff class.

For Mootools, firstly we need to make sure it’s loaded.

<!-- load the mootools library -->
<script type="text/javascript" src="mootools.js"></script>

Now we’ll wrap our Swiff object creation in Mootools domready event. This is the equivilant to what we did earlier in jQuery with the ready event.

window.addEvent('domready', function() {
var flash = new Swiff('test.swf', {
container: $('example'),
width: 1,
height: 1,
callBacks: {
onLoad: flashLoaded
}
});
});

Here we’re creating a new Swiff object, and telling it to place the flash object / embed tag it creates inside the div with the id of example like we did with the jQuery example. We specify the height and width both of 1 pixel and setup the callback.

As you can see, Mootools specifically calls this a callback unlike jQuery’s flashvars. They mean the same thing here, so we say the onLoad callback function in the Flash movie’s ActionScript will call the local JavaScript function flashLoaded.

Knowing When It’s Safe To Talk To Flash From JavaScript

I’ve been doing some work lately where JavaScript in an XHTML page needs to talk to some ActionScript 3.0 in a Flash movie.

The most common problem here is knowing when you can start talking to the Flash movie. The browser may have loaded all the scripts and started to execute them, but the flash movie may not have loaded or initialised at that point. If you try to talk to the movie at this point, you’ll get errors.

There are a couple of ways around this. You could code the flash movie into the page using <object> and <embed> html tags, then make sure your JavaScript calls the movie after the onload event has been called. E.g.

function flashLoaded() {
alert("Flash loaded");
}
window.onload = function() {
// flash should have loaded by now.
flashLoaded();
}

Now that isn’t ideal, the flash may have loaded, but the movie may not have initialised so you could still have problems.

The safest way is to include a callback function in your ActionScript that runs once the movie has finished initialising. This will call some JavaScript on your page letting you know the movie has loaded and can be interacted with. We can use the ExternalInterface class in the ActionsScript to achieve this.

Let’s assume our ActionScript class is called test, and we have a function in our JavaScript called flashLoaded. The following code is a quick way to let the JavaScript know the movie has loaded.

public function test():void
{
ExternalInterface.call("flashLoaded");
}

This is great, but it does mean we’ve had to hardcode the name of the calling function. What if we had two Flash movies in the page and they both called this function. This could cause problems. We need a way to pass in a function name dynamically.

Flash has something that used to be called FlashVars that can help us here. It’s basically a list of parameters and values that are passed and appended as a query string to the end of the movie files name. These are then available to ActionScript. In our object we alter the movie paramter accordingly.

<-- in the flash object tag -->
<param name="movie" value="test.swf?onLoad=flashLoaded" />

If you use the embed tag, make sure you alter the movie parameter there as well.

To see the passed parameters in ActionScript was need to use root.loaderInfo.parameters. Our initialiser function should be altered to use the following code, in this case we want to use the onLoad parameter.

public function test():void
{
ExternalInterface.call(root.loaderInfo.parameters.onLoad);
}

Great, we can now vary our the name of our callback. However problems could still occur. The movie may be loaded but the stage may not be ready. We need to add a little bit more wrapping code to handle this. The following code should do the trick.


package {
import flash.display.Sprite;
import flash.events.*;
import flash.external.ExternalInterface;
public class test extends Sprite
{
public function test():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
ExternalInterface.call(root.loaderInfo.parameters.onLoad);
}
}
}

As you can see we’ve moved the callback into the init function, and this is only called when the stage is ready.

You should now be safely able to script your flash movie from JavaScript.

See Knowing When It’s Safe To Talk To Flash From JavaScript – Part 2 for examples on how to integrate this with a modern JavaScript library like jQuery.

getURL and Flash 9

We upgraded our Flash players to the current version today and found a few slides on our sites didn’t work as expected.

When clicked, they were supposed to take you to other pages, but with the upgrade, old code was found to be broken.

Looking around, it appears the security model changed and we weren’t aware of this. I think it’s time to subscribe to the Flash RSS feed to keep on top of bug fixes and upgrades.

Anyway, it turned out our code could be fixed by just setting AllowScriptAccess to be “always” or “sameDomain”, depending on the application. In the <object> tag this was achieved by adding…

<param name="allowScriptAccess" value="always">

… and in the embed tag…

allowScriptAccess="always"

Those of you using SWFObject, the following JavaScript code does the trick…

so.addParam("allScriptAccess", "always");

This means when we call getURL() from ActionScript it is able to navigate to other pages on a foreign or the same domain.

There is a bit more information on this on the Adobe Flash knowledge base, Links from SWF files in HTML page no longer function (Flash Player 9).