Tuesday, March 28

NodeJS, Socket.io: Simple Client / Server


Introduction

The minimum amount of code to have NodeJS serve a simple socket.io client and server.



Requirements

This code uses NodeJS module "socket.io" which you install with the following command:
npm install socket.io


Server.js Source Code

var http = require('http')
 , fs = require('fs')

 , webpage = fs.readFileSync(__dirname + '/client.html')
 , port = 2017
 ;

// Send client.html to all requests
var server = http.createServer(
 function(req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end( webpage );
 }
);

// Socket.io server listens to our app
var io = require('socket.io').listen( server );

// Send current time to all connected clients
function sendEveryone( msg ) {
 io.emit('msg', msg );
}


// Listen for connections
io.on('connection', function( socket ) {
    // Single Client's socket
    socket.emit('confirm', 'Server here');
    socket.on('from Client', function( msg ){
     console.log( msg );
   });
});

server.listen( port );




client.html Source Code

<!doctype html>
<html>
<head>
   <script src='/socket.io/socket.io.js'></script>
</head>
<body>

 <script>
   var socket = io();

   socket.on( 'welcome' , function( msg ) {
       console.log( msg );

       // Contact Server
       socket.emit('from Client', 'Client Here');
   });

   socket.on( 'msg' , function( msg ) {
       console.log( 'incoming:' , msg );
   });

 </script>
</body>
</html>

0 comments :

Post a Comment