Plugging Into Socket.IO: The Basics

WebSockets are starting to become available in more and more browsers. In fact, at this point in time, pretty much the latest version of every browser supports it according to Can I Use. The best part, though, is that you don’t even need a modern browser with WebSockets available in order to utilize the real-time back-and-forth communication between the browser and server that it offers. Socket.IO will show you how it’s done.

According to the Socket.IO website:

Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It’s care-free realtime 100% in JavaScript.

Socket.IO gives you a simple, event-based JavaScript API that allows you to communicate between the server and client effortlessly in real time. Its default mechanism is WebSockets, but if WebSockets aren’t implemented in the user’s browser, it resorts to fallbacks such as Flash and AJAX long polling. This makes it available for a huge number of browsers, as you can see here.

The normal Socket.IO library is written in JavaScript for both the front end and the back end, so it was designed to run on a Node.js server. This is the context in which I’ll be talking about it, but you might be interested to know that others have ported the back end piece into other languages, which you can see listed at the bottom of the main Socket.IO wiki page.

Using Socket.IO Server Side

The easiest way to get Socket.IO setup for use on the server side is to install it via NPM:

1
npm install socket.io

That was easy. Now we need to start using it in our server side application code. The first thing we need to do is require the library and start listening for events coming in from the client side. You can listen via an Express server, or just tell it to use its own.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var io = require('socket.io'),
express = require('express');

// Via Express 3.x server
var app = express(),
server = require('http').createServer(app),
io = io.listen(server);
server.listen(80);

// Via Express 2.x server
var app = express.createServer(),
io = io.listen(app);
app.listen(80);

// Standalone
io = io.listen(80);

// Now let's set up and start listening for events
io.sockets.on('connection', function(socket) {

// We're connected to someone now. Let's listen for events from them
socket.on('some event', function(data) {

// We've received some data. Let's just log it
console.log(data);

// Now let's reply
socket.emit('event', {some: "data"});
});
});

There’s a lot going on here. The first three blocks just show different way we can set up a Socket.IO server for listening to the client. Note that 80 is a port number that you’re listening on. You can very easily have Socket.IO listen on a separate port from the one that your normal application server is running on, but you definitely don’t have to.

The next block of code is the interesting part. First we call io.sockets.on('connection', function(socket) {…}); which just waits around for a client to try to connect to it. Once it receives a connection, it creates a socket object and passes it into this callback function. This object is used to communicate directly with this single client that connected. In a bit I’ll show you how to broadcast messages to every connected client. For now, though, we need to learn how to do it with a single client.

Inside this callback we start to set up more listeners with socket.on. In the above example we’re listening for the client to emit “some event”. When a client emits that message, the callback sent into socket.on will be called. Notice that the callback function has an argument (data), which contains data sent with the message from the client. In our callback function we just log it. Then we emit a message back to the same client with socket.emit. The first argument that we pass in is the name of the message or event that the client should be listening for, similar to the way we’re listening for messages from the client. Then we pass in any data we want to send along with the message.

It really is that simple. We listen for messages from the client and react to them, and we send messages to the client. Like I said earlier, you can also broadcast messages to all of the connected clients, rather than to just a specific one. For example, in the case of a chat room, every time someone sent a message or connected, we’d need to let everyone see it.

1
2
3
4
5
6
io.sockets.on('connection', function(socket) {
// We're connected to someone now. Let's listen for events from them
socket.on('chat message', function(msg) {
io.sockets.emit('message', msg);
});
});

Rather than calling emit on socket, we call it on io.sockets, which will send the message to every client.

Moving on to the Client

You saw how simple it was to use Socket.IO on the back end right? It’s simply a two-way event-based messaging system. Sadly, the simplicity of the back end API doesn’t transfer to the front end. I’m just kidding. The front end API is essentially the same. Before we can take a look at the API, though, we have to add the script to our application.

It actually took me quite a while to find the client-side script. Other tutorials on the internet didn’t prove to be of much help. However, I did find out that there is a separate GitHub repo for the Socket.IO client script. You can find the file you want in the “dist” folder. I use it this way, but this isn’t the only way to serve the client-side JavaScript to the browser. It turns out that the back end Socket.IO server will serve you the front end script for you. Just point to the URL of the IO server and add “/socket.io/socket.io.js” to the end of it and you’ve got your script. If you’re one of those cool people who are using the same port as your Express server, you can use a relative URL for the script:

1
2
3
4
5
<!-- Normally -->
<script src="http://<uri:port>/socket.io/socket.io.js"></script>

<!-- If same port as Express -->
<script src="/socket.io/socket.io.js"></script>

Yay! Now we can use the script! First we need to connect to the back end. It’s really simple; just call a function and give it the URL of the Socket.IO server:

1
var socket = io.connect("http://<uri:port>/");

Now we’ll use socket in a very similar way to how it was used on the back end.

1
2
3
4
5
6
7
8
9
10
11
socket.on("connect", function() {
// Do stuff when we connect to the server
});

socket.on("some event", function(data) {
// Log the data I received
console.log(data);

// Send a message to the server
socket.emit("other event", {some: "data"});
});

As you can see, it’s different when trying to get a connection, but once the connection is made it is essentially the same code you use on the back end. I think it’s similar enough to the back end and simple enough that I won’t even bother explaining it.

So that was a pretty decent introduction, but you probably want more, right? Well there’s plenty more to get into, but this tutorial is already running a little long, so we’ll save that for a week from now. In the next post we’ll discuss namespacing, storage, configuration and more.

Conclusion

Two words sum this up: awesome, simple. It creates a super simple event-based API that allows us to have our applications communicate back and forth between the front and back ends effortlessly and in real time. If something happens on the server, your users can be immediately filled in on that information. The hardest thing about using Socket.IO is deciding the names to use for the messages.

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.