Setting up very basic server/client socketIO skeleton

SocketIO allows you to send messages back and forth between the server/client using a low-level socket mechanism. It has a shared interface for server/client, meaning you can write very similar js on server/client once the connection is established. SocketIO looks a little similar to nodes’ ‘net’ module.

Lets create the most simple implementation on the server:

‘server.js’

var http = require('http');
var io = require('socket.io');

var server = http.createServer();
server.on('request', function(req, res) {
  // typical HTTP code here...
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello werld!!! \n');
});

server.listen(8080);

var socket = io.listen(server);

socket.on('connection', function(client) {
  console.log('Client connected!');
});

here we have mostly predictable code, up until our socket code. We create a socket server by calling io.listen(server). An IO server doesnt deal with req/res as you do with an HTTP server. We then set an event handler for when there is a connection, where we just console.log() to notify there is a connection.

adding html file to send to client

this server-side io code doesnt do anything alone. We need to create a simple html file, load the socketIO library, and possibly jQuery & create an event handler for when the server pushes data related to the ‘connection’.

‘socket.html’

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>socketz are cool</title>

</head>
<body>

  <div id="display"></div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io.connect('http://localhost:8080');
    socket.on('connection', function(data) {
      console.log(data);
    })
  </script>

</body>
</html>

we are telling socketIO, once there is a connection, console.log() the data that was pushed through from the server.

Lets update our ‘server.js’ to serve the ‘socket.html’ file, and to output the clients info:

‘server.js’

var http = require('http');
var io = require('socket.io');
var fs = require('fs');

// syncronously read socket.html
var sockFile = fs.readFileSync('socket.html');

server = http.createServer();
server.on('request', function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  // send the syncronous sockFile
  res.end(sockFile);
});

server.listen(8080);

var socket = io.listen(server);

socket.on('connection', function(client) {
  console.log('Client connected!');
  // client has unique id
  console.log('Welcome client ' + client.id);
});

Now instead of just writing ‘Hello world’ to the client, it sends a html file which has socketIO setup, which will just console.log() the data sent. Each individual client has a unique key on .id.