Socket.io with Hapi.js

I recently got to work with hapi.js for building an api and I like the Hapi way. To add web-sockets I needed to integrate Socket.io.

Because I couldn’t find an up to date explanation on how to do this:


var Hapi = require('hapi');

var server = new Hapi.Server();

server.connection({ 

    host: 'localhost', 

    port: 8000 

});



var io = require("socket.io")(server.listener);



io.on("connection", function (socket) {

    console.log('connected');

    // Do all the socket stuff here.

})



server.start();



In your html do the usual:


<!DOCTYPE html>

<html>

    <head>

        <title>{{title}}</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

        <script src="/socket.io/socket.io.js"></script>

		<script>

			$(function () {

  				var socket = io.connect('http://localhost:8000');

				socket.on('topic', function (data) {

					// do something with data

				});

			})

		</script>

    </head>

    <body>

        

    </body>

</html>