পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Wednesday, February 8, 2017

Socket.IO - Hello World

Create a file called app.js and enter the following to set up an express application:
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
We'll need an index.html file to serve, create a new file called index.html and enter the following in it:
<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <body>Hello world</body>
</html>
To test if this works, go to your terminal and run this app using
nodemon app.js
This will run your server on localhost:3000. Go to your browser and enter localhost:3000 to check this.
This set up our express application and is now serving a HTML file on the root route. Now we will require socket.IO and will log "A user connected", everytime a user goes to this page and "A user disconnected", everytime someone navigates away/closes this page.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Whenever someone connects this gets executed
io.on('connection', function(socket){
  console.log('A user connected');

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
The require('socket.io')(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc events in it, using the socket object.
We have set uo our server to log messages on connections and disconnections. Now also need to include the client script and initialize the socket object there so that clients can establish connections when required. The script is served by our io server at '/socket.io/socket.io.js'. After doing the above, the index.html file will look like:
<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
  </script>
  <body>Hello world</body>
</html>
If you go to localhost:3000 now(make sure your server is running), you'll get Hello world printed in your browser. Now check your server console logs, it'll show a message:
A user connected
If you refresh your browser, it'll disconnect the socket connection and recreate. You can see this on your console logs:
A user connected
A user disconnected
A user connected
We now have socket connections working. This is how easy it is to set up connections in socket.IO.

No comments:

Post a Comment