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.

Repair A Fordham Elan Toilet

This post is a bit of change from the normal media and programming related stuff I tend to put up here, it’s about how I fixed my broken toilet.

This has been my first attempt at plumbing and I though it may be useful for others to see what I did.

Inside a fordham elan

My toilet (a Fordham Elan) decided to stop flushing after a few weeks of needing multiple pulls on the chain to get the water flowing. Looking online, it sounded like the flush valve on the syphon had gone. The only way to get this working again was to replace the siphon.

tools to fix a fordham elan

The Fordham Elan is an old model, and there were no spare parts available that I could track down. Thankfully I live near a plumbers merchant called Plumbers Mate and they suggested that a Macdee Metro Oblong Adjustable 6/7/9 Litre Flush Siphon should be a workable replacement. I bought this for a bargain £8.30, along with a tube of Plumba Joint Clear, a wrench and a piece of hose.

stop the water

The first job was to drain the tap. Initially I tied up the floating ball valve, but then realised that the slightest knock would send water into the tank. I then notice a small valve on the water inlet. Just a 90degree turn of this turned the water off and I was able to drain the tank. This was just a case of placing the hose in the tank, sucking until a stream of water appeared, and letting this empty into the toilet. The remaining water in the tank was removed using a car sponge.

stop the water by turning this valve

Now the tank was empty, the next job was to remove the siphon. These are two screw connectors on the downpipe, I undid these to release the syphon. It took quite a while as the wrench I had wasn’t quite the right size, but it did the job in the end. I wasn’t able to lift the siphon as the floating ball was in the way, this had to be unscrewed and removed before the siphon could be lifted.

Looking inside the plastic at the bottom had perished.

an empty fordham elan

The new siphon was rested in place, but the Fordham Elan has four small notches near the down pipe to hold their own siphon in place. The generic one I had bought didn’t have these, so I removed them with a pair of pliers.

I placed a rubber O ring on the bottom of the new siphon, ran some of the Plumba Joint around it, then screwed it into place. On my first attempt I over tightened and this forced the O ring off the pipe. The joint needs to be tight, but not that tight. The Plumba sealant needs to dry for a few minutes, so I gave it 10 to be on the safe side. While it was drying I reattached the ball float.

the new syphon in the fordham elan

It was now time to turn the water back on, gently I turned the valve and let the tank fill a little while I checked for leaks. None occurred, so after 5 minutes I let the tank fill. I did notice that the ball float was a little tight next to the new siphon, but it still worked and turned the flow off when the tank was full.

Finally it was time to flush. I placed a selected of towels under the cistern just incase of a flood but when pulled, the cistern emptied correctly into the toilet without a leak in sight.

I hope this has been of use to other budding plumbers. It’s saved me a few hundred pounds.

Faking A Fixed Background In An iOS Web App

If the lack of a fixed background image position has been bugging you when your building your HTML / CSS based iOS apps, then I thought I’d share a work around I’ve been using.

If you are creating a native app from this in XCode then you would almost certainly be embedding the web page in a UIWebView. This is where the magic works.

Create a UIImageView with your background image on, then place your UIWebView directly over this image.

In your Objective-C you need to set the UIWebView‘s background colour to clearColor and make the UIWebView opaque. If your UIWebView is called webView the following two lines of Objective-C will do this.

[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];

Your background image should now show through the webpage and be visible as the background.

iPhone Time Bug

I seem to have fallen victim of the iPhone daylight saving time bug that has affected owners in the southern hemisphere.

Today, my recurring alarms woke me an hour early.

The time at the top of the phone is an hour ahead of the time shown in the clock app.

It would seem the iPhone has forgotten the UK is still in British Summer Time for a few more days.

Very annoying!

MooTools 1.2 Beginners Guide Book Review

MooTools 1.2 Beginners Guide from Packt Publishing
After a year of using jQuery, I have an upcoming project that requires me to go back to MooTools. A lot of my MooTools knowledge was rather rusty, but a couple of weeks ago the nice people at Packt published a new book called MooTools 1.2 Beginner’s Guide and I managed to get my hands on a copy.

MooTools 1.2 Beginner’s Guide by Jacob Gube and Garrick Cheung promises readers they will “learn how to create dynamic, interactive, and responsive cross-browser web application using one of the most popular JavaScript frameworks”, and it certainly does that.

The book is very clearly written, with plenty of step by step examples. You’ll need a basic understanding of HTML, CSS and JavaScript but not much more.

The book starts out explaining what MooTools is, how to go about downloading it and then using it on a web page. It clearly explains the difference in using normal JavaScript code and MooTools code, before moving on to DOM selectors and other key utilities in the MooTools library. In addition to this, there are chapters on events, AJAX, animations and plugins.

When the book arrived I expected a very simple book, and I have to admit to having been pleasantly surprised. As well as being an excellent tutorial for beginners, there is actually quite a lot for the more experienced developer and I found myself picking up quite a few new tricks, and clarifying my knowledge in a few places. One area that MooTools has always been weak in comparison to rival frameworks like jQuery has been the quality of the documentation and tutorials for beginners, this book really addresses that area and should be a welcome addition to the library of any MooTools developer.

MooTools 1.2 Beginners Guide Official Website.

Stir Fried Pork On A Bed Of Wilted Pok Choi Recipe

Here is my recipe for delicious stir fried pork on a bed of wilted pok choi. It takes about 15 minutes to prepare and cook, so is perfect for a quick after work meal.

You will need the following ingredients…

  • Rice (white – half cup)
  • Pok Choi (2 or 3 heads cut in half)
  • Lean Pork (I use one loin steak)
  • 1tsp Sugar
  • 1tbsp Light Soy Sauce
  • 3tbsp Oyster Sauce
  • Pinch of Ground White Pepper
  • Garlic (1 clove – crushed and finely sliced)
  • A few Chilli Flakes
  • Groundnut Oil

Now, here’s how to put it all together.

  1. Cook the rice. For perfect white rice, use one part rice to two parts water. I use about half a cup of rice to one cup of boiling water. Cook covered on a gentle heat for 10 minutes, before removing from the heat and leaving to steam for a further 5 minutes. Don’t remove the lid of the pan during this time.
  2. Meanwhile, prepare the marinade by mixing together the sugar, light soy sauce, ground white papper and 1tbsp of the oyster sauce.
  3. Thinly slice the pork and add to the marinade. Leave for about 10 minutes.
  4. Heat the groundnut oil in a wok on a high heat until smoking, then add the marinated pork. Spread over the wok’s cooking surface and leave for about 15 seconds to seal on one side. Then stir fry until cooked (about 2 minutes).
  5. Remove the pork from the wok and add some more oil to the wok.
  6. Sprinkle a few chilli flakes into the hot oil, then add the pok choi. Leave for about 30 seconds, then add the crushed garlic and stir. After about a minute the pok choi will have wilted, turn the heat off and add the remaining 2tbsp of oyster sauce – mix well.
  7. Add the pok choi to a serving dish, placing the pork on top. Serve with the rice.

I enjoy this dish after a hard day at work. i hope you find it as tasty and delicious as I do.

Pork Pok Choi

Maintaining The Scroll Position On An ASP.NET Page After Postback

I had a requirement today for an ASP.NET page to jump to the same part of the page once a form was submitted via a postback.

Qudos to my fellow developer Andy Howell for leaping in and pointing out that functionality was already in ASP.NET 2.0 and above, so there would be no need for me to write any funky JavaScript.

You need to set MaintainScrollPositionOnPostback to true. I did this in the Page tag on the ASP.NET page.

<%@ Page MaintainScrollPositionOnPostback="true" %>

Although I’ve not tested it yet, you should also be able to set it globally in the web.config file in the pages section.

<pages maintainScrollPositionOnPostBack="true" />

Or programmatically in the code behind.

System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;

For more information on this, see the MSDN page for System.Web.UI.Page.MaintainScrollPositionOnPostBack.

Double Dash In HTML Comments

While working on FHM.com earlier today I came across an odd bug on a page. On Firefox 3, parts of the page were rendering incorrectly, while on Internet Explorer everything was fine.

Browsers rendering content differently isn’t anything new, but most of this site is derived from common templates, and only a small part of the page was directly inserting HTML. This was the obvious place to look.

Looking at the source code with syntax highlighting turned on revealed the problem, and it was one i’d not come across before.

The site had a comment that included two dashes next to each other, something like this

<-- A test comment -- test -->

Looks OK doesn’t it? Well it’s not valid XHTML, hence the problem.

XHTML is based on XML so follows it’s standards. Here is the standard for XML comments.

The key wording here is, the string ” — ” (double-hyphen) MUST NOT occur within comments.

The same applies to HTML, have a look at what the HTML4 spec says about comments. This is down to HTML being based on SGML, and double dashes are SGML comments.

In the end, it’s Firefox obeying the spec, and other browsers not. However, things look like they are due to change.

Due to these problems, SGML comments have been removed from Acid 2, and future HTML versions will not require SGML comments. Browsers that have implemented them are now expected to remove their support for SGML comments, for all HTML versions.

Read more about HTML and SGML comments.