Dec 052011
 

In my last post I went through installation and setup of some great new tools: node.js and socket.io. Now that we have node and socket.io installed, its time to play around a bit to understand how to use these new toys. In this post I’ll be writing a simple http server and some client-side html/javascript to go with it. (Note: I’m assuming readers have a basic understanding of html and javascript) My goal here is to go step by step, to see each piece fit together. People more experienced with client/server programming concepts may want to skim a little. You can also download the test code created here as files at the bottom of the post.

As a sanity check, make sure node is installed and in your path by typing

$ node -v

You should see something like

 

Now we’re ready to write some code. Let’s start with the server. Navigate to the directory you want to test out of, and make a file called socketio-test.js for your test server:  

$ touch socketio-test.js

Open this file in your favorite text editor. Start by defining some variables at the top:  

var http = require('http')
, url = require('url')
, server;

We’re only including the bare essentials here, enough to start our server and receive http requests. We won’t even included the socket.io library yet, but we’ll get to that soon. Now let’s define the server:  

server = http.createServer(function(req, res) {
  // server code
  var path = url.parse(req.url).pathname;
  switch (path) {
    case '/':
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('Hello!\n');
      res.end();
      break;
    default: send404(res);
  }
}),

send404 = function(res) {
  res.writeHead(404); 
  res.write('404'); 
  res.end(); 
};

server.listen(8080);

Ok, check out the above block of code. We are creating an http server object by instantiating that server variable we defined above using the http library. We are then defining its behavior by parsing any urls it receives and throwing the path of the url into a switch/case statement. Notice that we could define this behavior based on anything we wanted, not necessarily the url path. Here we have just defined a case for path ’/', so our server will only respond to requests to the root path. For these requests, it will send “Hello!” back to the client. For all requests to other paths, we have defined the send404 function, which will return 404 to the client. We will add more path handling as we go on.

Finally, we have told our server to listen on port 8080. Now, fire up the server!  

$ node socketio-test.js

You won’t see any output in the server terminal window, but the server is now running. Bring up a second terminal window to issue some requests to test the server. In a second command window, send a root request to the server with

$ curl localhost:8080

You should get a response similar to:

 

I’m using this snazzy blue terminal window for client-side commands, and sticking with green-on-black window for server output. Now we know our server can respond. Huzzah! Celebrate as necessary, and then it’s time to move on to bigger and better things. This server doesn’t do much, and our client is just a command line.

Let’s start by adding some functionality to our server, courtesy of socket.io.

var http = require('http')
, url = require('url')
, fs = require('fs')
, server;

server = http.createServer(function(req, res) {
  // your normal server code
  var path = url.parse(req.url).pathname;
  switch (path) {
    case '/':
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('<h1>Hello! Try the <a href="/socketio-test.html">Socket.io Test</a></h1>');
      res.end();
      break;
    case '/socketio-test.html':
      fs.readFile(__dirname + path, function(err, data){
        if (err) return send404(res);
        res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
        res.write(data, 'utf8');
        res.end();
      });
      break;
    default: send404(res);
  }
}),

send404 = function(res) {
  res.writeHead(404);
  res.write('404');
  res.end();
};

server.listen(8080);

// socket.io, I choose you 
var io = require('/usr/local/lib/node/socket.io').listen(server);

// on a 'connection' event 

io.sockets.on('connection', function(socket) {

  console.log("Connection " + socket.id + " accepted.");

  // now that we have our connected 'socket' object, we can 
  // define its event handlers 
  socket.on('message', function(message) { 
    console.log("Received message: " + message + " - from client " + socket.id); 
  });

  socket.on('disconnect', function() { 
    console.log("Connection " + socket.id + " terminated."); 
  });

});

We’ve added quite a few things here, let’s take stock. First, I’ve required the fs library, to access to some file I/O functions. I’ve changed the response values to html, since this is an http server, after all. I’ve also created a path for a socketio-test.html page, which I’ll create next, and put a message with a link to that page in the response for the root path.

Most importantly, I’ve added some socket.io code, which you can see at the bottom of the page. First, we require the socket.io library and in the same line, tell the resulting socket.io object to listen to our server object. Now it has access to all traffic coming over that server, and can perform tasks based on it. Then we just tell socket.io what to do for the various events it will encounter: ‘connection’, ‘message’, and ‘disconnect’. Notice that the ‘message’ and ‘disconnect’ events are defined inside the definition for the ‘connect’ event. We define all other events inside the ‘connection’ event definition, since they don’t really matter until a connection has occurred. Also, we could potentially define different types of custom connections, each with different event behaviors associated. In our example case, we’re just going to have our server send some output to the console logs that we can watch. Clean and simple, right? That’s the beauty of socket.io.

Now we have to write that client socketio-test.html page I’ve lead everyone to believe exists. Ok, I can man up. Here goes:

<!doctype html>
<html>
  <script src="/socket.io/socket.io.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  <body>
    <script type="text/javascript">
      var socket;

      function connect() {
        socket = io.connect(null);

        // Callbacks for standard socket.io server events
        socket.on('connect', function(){ status_update('Connected to Server'); });
        socket.on('disconnect', function(){ status_update('Disconnected from Server'); });
        socket.on('reconnecting', function( nextRetry ){ status_update('Reconnecting in ' + nextRetry + ' milliseconds'); });
        socket.on('reconnect_failed', function(){ status_update('Reconnect Failed'); });    
      }

      function status_update(status) {
        $('#status').html(status);
      }

      function disconnect() {
        socket.disconnect();
      }

      function send() {
        socket.send('Hello, Server!');    
      };  
    </script>

    <h1>Socket.io Test</h1>
    <div><p id="status">Waiting for input</p></div>
    <button id="connect" onClick='connect()'>Connect</button>
    <button id="disconnect" onClick='disconnect()'>Disconnect</button>
    <button id="send" onClick='send()'>Send Message</button>

  </body>
</html>

Take a look at the html/javascript above. First, on the html side, we just have three buttons and a div. These will perform standard actions from client to server. The div is for displaying status from our socket.io object. In javascript, we’ve defined a client-side socket.io object, which looks like:

socket = io.connect(host, [options]);

Since we are using localhost, we pass in null for the host parameter. We could also pass in ‘localhost’ to achieve the same effect. We then define behaviors of the socket object using

socket.on(action, function() )

For example,

socket.on('connect', function(){ 
  status_update("Connected to Server"); 
});

which calls our status_update javascript function when the socket connects.

Notice the fancy footwork surrounding the connect() function and our firstconnect variable. The reason for this is a small bug (or at least, an unintuitive behavior) of this version of socket.io. Once you call connect() and then disconnect() on a socket, calling connect() again does not reestablish the connection. To do this, you have to call socket.socket.reconnect(). So, to allow our client to use the same ‘Connect’ button to connect the first time, and all subsequent times, we need to keep track of whether we are connecting for the first time, so we can call reconnect on all connections attempts after the first. Remember this quirk, it has the potential to make very annoying bugs.

Ok, time for a test. Start your node server again, to get all of the changes we made (shut it down if it was still running, then restart). Check the server command line – since we now have socket.io running on the server, startup output should look something like

Open up a browser and go to http://localhost:8080.  You will see:

Theres the link we added to the root path server response of the server – click it to go to te socket.io test page we just finished. You should see:

Now click the Connect button. You will see “Waiting for input” change to “Connected to Server”, meaning our socket.on(‘connect’) function was invoked. Go back to the server terminal window:

We can see that the connection was initiated via websocket, and the server has assigned me a client session id. Since its socket.io, the connection could have been initiated via any number of technologies, depending on my browser and network situation. If you watch the server output for a while, you will also see it set and clear heartbeat timeouts for our client, and report receiving heartbeat packets. This is socket.io making sure our client has maintained a persistent connection. It will terminate the connection if the client stops responding for too long. Go ahead and try out the Disconnect and Send Message buttons as well, which will also show output on the server  

The above output is the result of disconnecting our initial session, connecting again (note the new client session id), and sending a message of “Hello Server!”.

That’s it! Now you have a working socket.io server and a client page to interact with it. We’ve gone through the basics of client/server communication, and you should be able to expand this example code into something much more functional with a little javascript.  

Get 50% off my Node.js course here

If you liked this article, help me out by sharing a 50% discount to my Node.js course here: Thanks!

You should follow me on Twitter here:

  • Reinoud

    Very helpful tutorial, thanks a lot! :)

    • http://www.codehenge.net Constantine Aaron Cois

      Glad to help!

  • Reinoud

    One thing I don’t get though – the ‘message’ paragraph in the HTML doesn’t seem to do anything? Or am I doing something wrong? How do I make the server talk to the client?

    Thanks in advance

    • http://www.codehenge.net Constantine Aaron Cois

      You are correct, it doesn’t do anything in this code. Its a placeholder for a future version of the tutorial.

      If you want to talk to the client, start by looking at the broadcast method.

      • Reinoud

        Ah good. I eventually made a chat box out of it using an array with all the sockets in it and iterating over all sockets when the server receives a message, calling the send()-method to send it to everyone connected.

        I assume the broadcast()-method does that thing for me ;-) . Thanks!

  • John Miller Crawford

    Marvellous stuff! This is the most helpful socket.io post that I’ve come across! Even though it’s written for the Mac OSX, I found it all worked on my Win7 machine. Many many thanks for posting.

    • http://www.codehenge.net Constantine Aaron Cois

      Your welcome! Feel free to share it. I’m also working on a full online introductory course for node.js, so stay tuned!

  • peboer

    Thanks for posting this. I’ve been trying to get all this stuff up and running, and this is the tutorial that did it for me. One thing that can be a gotcha for newbies like me (who are used to old school ways of ‘global everything’) is the include line:
    var io = require(‘/usr/local/lib/node/socket.io’).listen(server);
    I found the installation notes for all this stuff a bit lacking in their attempt to be comprehensive! The crux of it is that when you use npm to install socket.io (or any other package), you’ll probably want to navigate to the directory of this practice project (where you keep the socketio-test.js file) and then do the “npm install socket.io” to put a local copy of socket.io in with this project. Based on doing that, the include line becomes:
    var io = require(‘./node_modules/socket.io’).listen(server);
    This may seem obvious, but it is worth commenting, at least that this is the part that may not work if you cut and paste the example!
    Thanks again,
    Peter.

  • Itai Roded

    I Think it’s the first time i’m posting… You deserve a HUGEEEE thank you!! Finally i found a basic tutorial, sooooo hard to find.. Any more like these? someone?
    Also i found a bug, In the server, Will bring up: GET http://localhost:8080/json.js 404 (Not Found)
    Doesn’t effect the socketIO functionality, but why is it there from the first place?

    • Itai Roded

      And for me (as for the comment below me) i had to make the line like that:
      // socket.io, I choose you
      var io = require(‘socket.io’).listen(server);
      instead of
      var io = require(‘/usr/local/lib/node/socket.io’).listen(server);

    • http://www.codehenge.net Constantine Aaron Cois

      Its only there to make IE behave nice. I haven’t tried it in IE lately, it may no longer be necessary.

  • Arnaud

    Hi,
    i launched the server, then tryed to push connect button and i get that :

    io is not defined
    [Break On This Error]

    socket = io.connect(null);

    that’s correct, i wonder where the io object is defined…
    my link to script is :

    what’s wrong ?

    • Arnaud

      sorry, that is because i have node v0.6.11….

  • Joel Hopkins

    Hi Constantine,

    Awesome work. Easy to follow.

    I’m running into an issue, and here is what it spits out when I try to start the test server.

    Mac-Unibodys-MacBook:chat_test macunibody$ node socketio-test.js

    node.js:134
    throw e; // process.nextTick error, or ‘error’ event on first tick
    ^
    Error: Cannot find module ‘/usr/local/lib/node/socket.io’
    at Function._resolveFilename (module.js:317:11)
    at Function._load (module.js:262:25)
    at require (module.js:346:19)
    at Object. (/Applications/MAMP/chat_test/socketio-test.js:37:10)
    at Module._compile (module.js:402:26)
    at Object..js (module.js:408:10)
    at Module.load (module.js:334:31)
    at Function._load (module.js:293:12)
    at Array. (module.js:421:10)
    at EventEmitter._tickCallback (node.js:126:26)

    From what I’ve found (http://stackoverflow.com/questions/7873517/heroku-says-cannot-find-module-socket-io), I might need to “add socket.io in dependencies in package.json,” but within npm, there are 15-20 package.json files. Any idea which one? or if that is even going to be the solution?

    Thanks for the good work.

    • http://www.codehenge.net Constantine Aaron Cois

      Hi Joel. Is “/usr/local/lib/node/socket.io” the correct path for the socket.io library on your system?

      Also, this shorthand notation may work, if your paths are set up properly:

      io = require(‘socket.io’)

  • exomic

    Hi,

    Excellent tutorial! Good job!

    The problem is when I start using Socket.IO I always get this error when I go on http://localhost:8080 to test the page.

    /usr/local/lib/node_modules/socket.io/lib/manager.js:0
    (function (exports, require, module, __filename, __dirname) { /*!
    ^
    RangeError: Maximum call stack size exceeded

    Any ideas?

    • http://www.codehenge.net Constantine Aaron Cois

      That error is common when the server is overloaded – have you made any changes to the code? Adding, for example, a recursive call or something would do it.

      Can you tell me when exact version of node.js and socket.io you are using?

      • exomic

        node -v:
        v0.7.8-pre
        socket.io 0.9.4

        • http://www.codehenge.net Constantine Aaron Cois

          That’s a potentially volatile pre-release version of node – i’d give it a shot on an active release first, to see if it behaves the same way

  • DS kanth

    Fantastic tutorial… could see the power and possibilities of node.js and socket.io

  • Chandan Dey

    Hi,
    I am using Node version 0.7.8 install in (C:/Program Files (x86)/nodejs) with modules path for socket.io version 0.9.5 (C:/Program Files (x86)/nodejs/node_modules/socket.io/lib/socket.io.js). I have changed the path for socket.io with that in C:Program Files (x86)nodejssocketio-test.js file. And use script file in C:Program Files (x86)nodejssocketio-test.html like [this file was downled from JSON site and kept into root directory] and
    I just run the “socketio-test.js” file it will running properly and shows a message (info – socket.io started). When I hit the “Connect” button in socketio-test.html file it will gave an error (‘io’ is undefined) in IE, Mozila Firefox & Google Chrome. Please help me to short out this error.
    Thanks
    Chandan
    (email id : chandan.0@gmail.com)
    Note:
    *** My folder structure id :
    C:/Program Files (x86)/nodejs [nodejs installed directory]
    C:Program Files (x86)nodejsnode_modulessocket.iolib [socket.io isntalled directory]
    *** Change in “socketio-test.js” file
    var io = require(‘C:/Program Files (x86)/nodejs/node_modules/socket.io/lib/socket.io’).listen(server);
    *** Change in “socketio-test.html” file

    • http://www.codehenge.net Constantine Aaron Cois

      Hi Chanden.

      Looks like your server code is fine, and the problem is on your client side. This means that this line:

      is unable to include the file socket.io.js. Are you seeing an error in your dev tools indicating that this file isn’t loaded?

  • Chandan Dey

    Hi Constantine,
    Thanks for your quick reply.
    I solved the problem using the socket.io.js after hosted in IIS and use like :
    http://localhost:8124/socket.io/socket.io.js

    Now I want to do send request from HTML5 client to Node.js server to calculate two number addition.
    My requirement like this:
    I have a HTML5 page with 2 text boxes 1 lable and a Button called “Add”. User input 2 numbers into 2 text box and press the “Add” button. In my logic HTML5 client send 2 numbers to Node.js server as parameter/argument after that Node.js server add 2 numbers and returned the result to HTML5 client and the result will display in the lable.

    Is it possible? If yes please guide me to solve this problem.
    Thanks in advance.
    Chandan Dey

    • http://www.codehenge.net Constantine Aaron Cois

      Yes, you can do this in a few different ways. You could have the server emit another event to the client with the answer, or you could pass in a function (remember, functions are first class citizens in Javascript) to the server as a parameter in your ‘add’ event, which the server can then call, passing your client the result as an input parameter.

      If that doesn’t make sense, let me know, I can try to provide some examples.

      I actually have a course entitled “Learn Node.js by Example” that will be released on udemy.com in less than a week which shows some examples of this behavior. Check it out if you are interested in more structured learning.

      • Dey Chandan

        Hi Constantine,
        Thanks for your quick reply. Actually I am unable to reply through this site most of the time message was posted but after refresh the page my reply was not shown. Don’t know why. Hopefully this message properly send to you.
        I am already tried with the “emit” method but not success.
        I want to do send userid/password from HTML5 client to Node.js server and validate with MySQL database and return the result to client.
        My code:
        server_test.js :
        var io = require(‘C:/Program Files (x86)/nodejs/node_modules/socket.io/lib/socket.io’);
        var socket = io.listen(8124);
        socket.sockets.on(‘connection’,function(socket){
        socket.on(‘login’, function(data, usr, pass){
        var mysql = require(‘mysql’);
        var TEST_DATABASE = ‘employee’;
        var TEST_TABLE = ‘tblusers’;
        var client = mysql.createClient({
        user: ‘root’,
        password: ‘secret10′,
        });

        client.query(‘USE ‘+TEST_DATABASE);

        client.query(
        ‘SELECT name FROM ‘+TEST_TABLE+’ WHERE user = ‘+usr+’ AND password = ‘+pass,
        function selectCb(err, results) {
        if (err) {
        throw err;
        }
        socket.emit(‘retuLogIn’,{username: results[0]['name']});
        client.end();
        }
        );
        });
        socket.on(‘disconnect’, function(){
        console.log(‘Server has disconnected’);
        });
        });

        client_test.html

        WebSocket Client Demo [socket.io]

        function connect() {
        try
        {
        var socket = io.connect(‘http://localhost:8124/’);
        socket.on(“connect”,function(){
        document.getElementById(‘status’).innerHTML =”Browser has connected to the app server”;
        });
        socket.on(‘login’, function (data, document.getElementById(‘txtUser’).value, document.getElementById(‘txtPass’).value) {
        document.getElementById(‘status’).innerHTML = ‘Welcome ‘+data.username;
        });
        }
        catch(err)
        {
        document.getElementById(‘status’).innerHTML = err.message;
        }
        }

        WebSocket Client Demo
        Enter user and password to Log-In
        User :

        Password :

        Log-In

        Please help me to sort out this problem.
        Thanks in advance
        Chandan Dey

      • Dey Chandan

        Hi Constantine,
        Thanks for quick reply.
        Can you please try a small example for me about passing 2 parameter from HTML5 client and receive the parameter value in Node.js server and calculate the 2 numbers and return the result to HTML5 client and display in a lable. Actually I have already spend 3 days on it but no success.
        Thanks in advance.
        Chandan Dey

      • Dey Chandan

        Hi Constantine,
        Thanks for your previous help.
        Can you have any small test application to solve my previous mention problem.
        1) Send 2 integer value from HTML5 text box after Click “Add” button and calculate the sum of 2 param value in Node.js server and return the result and show in HTML5 page.

        OR

        2) Another one is verify userid/password send from HTML5 validate in Node.js (socket.io) and return the result in HTML5 page.
        I am sending my test application but did not work :
        I want to do send userid/password from HTML5 client to Node.js server and validate with MySQL database and return the result to client.
        My code:
        server_test.js :
        var io = require(‘C:/Program Files (x86)/nodejs/node_modules/socket.io/lib/socket.io’);
        var socket = io.listen(8124);
        socket.sockets.on(‘connection’,function(socket){
        socket.on(‘login’, function(data, usr, pass){
        var mysql = require(‘mysql’);
        var TEST_DATABASE = ‘employee’;
        var TEST_TABLE = ‘tblusers’;
        var client = mysql.createClient({
        user: ‘root’,
        password: ‘secret10′,
        });

        client.query(‘USE ‘+TEST_DATABASE);

        client.query(
        ‘SELECT name FROM ‘+TEST_TABLE+’ WHERE user = ‘+usr+’ AND password = ‘+pass,
        function selectCb(err, results) {
        if (err) {
        throw err;
        }
        socket.emit(‘retuLogIn’,{username: results[0]['name']});
        client.end();
        }
        );
        });
        socket.on(‘disconnect’, function(){
        console.log(‘Server has disconnected’);
        });
        });

        client_test.html

        WebSocket Client Demo [socket.io]

        function connect() {
        try
        {
        var socket = io.connect(‘http://localhost:8124/’);
        socket.on(“connect”,function(){
        document.getElementById(‘status’).innerHTML =”Browser has connected to the app server”;
        });
        socket.on(‘login’, function (data, document.getElementById(‘txtUser’).value, document.getElementById(‘txtPass’).value) {
        document.getElementById(‘status’).innerHTML = ‘Welcome ‘+data.username;
        });
        }
        catch(err)
        {
        document.getElementById(‘status’).innerHTML = err.message;
        }
        }

        WebSocket Client Demo

        Enter user and password to Log-In

        User :

        Password :

        Log-In

        Please help me to sort out this problem.
        Thanks in advance
        Chandan Dey

        • http://www.codehenge.net Constantine Aaron Cois

          To #1:

          The easiest way is to add an onclick function to the Add button, let’s call it “add”:

          function add() {
          socket.emit(‘add’, val1, val2, function(result) {//display result});
          }

          So here I’m emitting an event from the client called ‘add’. The server can then receive this event by having something like:

          socket.on(‘add’, val1, val2, function(fn) {
          //do addition, call fn(result) to send result back to client
          });

          I’m passing in the two values, and also a callback function from the client. The server can use this callback function to give the result data back to the client.

          Make sense?

          I’ll be working on some more blog posts this summer to get into these techniques in detail. In the meantime, you can check out my Learn Node.js by Example course for thorough examples and walkthroughs.

          • Dey Chandan

            Hi Cois,
            Thanks for your reply.
            I have tried with your guide but not yet success.
            This is my code as per your instruction.

            html_Server.js
            ——————–
            var io = require(‘socket.io’);
            var socket = io.listen(8124);
            socket.sockets.on(‘connection’,function(socket){
            socket.on(‘add’, val1, val2, function(fn) {
            val1+val2, function(result){}
            });
            socket.on(‘disconnect’, function(){
            console.log(‘Server has disconnected’);
            });
            });

            html_Client.html
            ———————–

            WebSocket Client Demo

            var socket = io.connect(‘http://localhost:8124/’);
            socket.on(“connect”,function(){
            alert(“Client has connected to the server”);
            });

            function add() {
            val1=document.getElementById(‘txtUser’).value;
            val2=document.getElementById(‘txtPass’).value;
            socket.emit(‘add’, val1, val2, function(result) {document.getElementById(‘status’).value=result});
            }

            Add Test
            Enter two number to Add
            Number 1 :

            Number 2 :

            Add

            If you have some time, please rectify my code. I had a plan to subscribe your Learn Node.js by Example course shortly.

            Thanks in advance.
            Chandan Dey

          • roballcon

            It works when I change the server code to:

            socket.on(‘add’,function(val1,val2,fn) {
            fn(val1+val2);
            });

          • Dey Chandan

            Hi Cois,

            Could you please rectify my code to working properly. Then I can move further with node.js with HTML5.

            Thanks
            Chandan

          • http://www.codehenge.net Constantine Aaron Cois

            Chandan – there are a few problems with the code you posted, let me take a look and i’ll post some fixes soon.

          • Dey Chandan

            Hi Cois,

            Thanks for your reply. Let me try with your suggestion and get back to you.

            And definitely I will post my next question if any into StackOverflow site. Infact I was already post this issue in StackOverflow on 1st June. The URL is :

            http://stackoverflow.com/questions/10818636/html5-page-logging-with-mysql-database-in-node-js-with-socket-io

            Thanks
            Chandan Dey

          • Deychandan

            Hi Cois,
            I have tried with some change code as per your references but did not success. I am sending you code please go through my code try to find my mistake.
            server.js
            ======
            var app = require(‘http’).createServer(handler)
            , io = require(‘socket.io’).listen(app)
            , fs = require(‘fs’)
            , mysql = require(‘mysql’)

            var client = mysql.createConnection({
            host: ‘localhost’,
            user: ‘root’,
            password: ‘abcd1234′,
            });

            client.connect();

            app.listen(3232);

            function handler (req, res) {
            fs.readFile(__dirname + ‘/index.html’,
            function (err, data) {
            if (err) {
            res.writeHead(500);
            return res.end(‘Error loading index.html’);
            }

            res.writeHead(200);
            res.end(data);
            });
            }

            io.sockets.on(‘connection’, function (socket) {
            socket.on(‘login’, function(usr, pass){
            var TEST_DATABASE = ‘nodejs_mysql_test’;
            var TEST_TABLE = ‘test’;

            client.query(‘USE ‘+TEST_DATABASE);

            client.query(‘SELECT title FROM ‘+TEST_TABLE+’ WHERE user = “‘+usr+’” AND password = “‘+pass+’”‘, function(err, results) {
            if (err) throw err;
            console.log(results[0]); // [{1: 1}]
            socket.emit(‘retuLogIn’,results[0]['title']);
            });

            });
            socket.on(‘disconnect’, function(){
            console.log(‘Server has disconnected’);
            });
            });

            client.html
            ========

            WebSocket Client Demo [socket.io]

            function connect() {

            try
            {
            var socket = io.connect(‘http://localhost:3232/’);
            socket.on(“connect”,function(){
            document.getElementById(‘status’).innerHTML =”Browser has connected to the app server”;
            socket.emit(‘login’, document.getElementById(‘txtUser’).value, document.getElementById(‘txtPass’).value);

            });
            socket.on(‘retuLogIn’, function (data) {
            document.getElementById(‘status’).innerHTML = ‘Welcome ‘+data;
            });
            }
            catch(err)
            {
            document.getElementById(‘status’).innerHTML = err.message;
            }
            }

            WebSocket Client Demo
            Enter user and password to Log-In
            User :

            Password :

            Log-In

            Thanks in advance
            Chandan

          • Deychandan

            Hi Cois,

            Could you please see and rectify my code which I was posted last week to working properly. I can not understand the problem.

            the error is :
            =========
            C:Program Files (x86)nodejs>node “C:Program Files (x86)nodejsapp.js” info – socket.io started

            C:Program Files (x86)nodejsapp.js:6
            var client = mysql.createConnection({
            ^ TypeError: Object # has no method ‘createConnection’
            at Object. (C:Program Files (x86)nodejsapp.js:6:24)
            at Module._compile (module.js:449:26)
            at Object..js (module.js:467:10)
            at Module.load (module.js:356:32)
            at Function._load (module.js:312:12)
            at module.js:487:10
            at EventEmitter._tickCallback (node.js:238:9)

            C:Program Files (x86)nodejs>

            Thanks
            Chandan

          • http://www.codehenge.net Constantine Aaron Cois

            Chandan,
            Look at the error message. It is throwing an error on the createConnection method of the mysql module – which is well outside the scope of this tutorial. However, I’d guess one of two things is wrong.

            1) have you installed the mysql module? (npm install mysql)

            2) You are using the createConnection method incorrectly. From the node-mysql docs:

            var mysql = require('mysql');
            var connection = mysql.createConnection({
            host : 'example.org',
            user : 'bob',
            password : 'secret',
            });

            Maybe you need to pass something in in the ‘host’ parameter?

      • Dey Chandan

        Hi Constantine,
        Can I get any help from you about my last 2 posts.

        Thanks
        Chandan

  • http://www.facebook.com/duby1 Aron Duby

    Finally a good tutorial that explains things more than just throwing code at you! Thank you so much!

    • http://www.codehenge.net Constantine Aaron Cois

      You’re welcome!

  • Nachiketha

    AWESOME!! :)
    Really a great tutorial.. keep posting abt related topics..
    Finally im able to write some meaningfully working code..!

    • http://www.codehenge.net Constantine Aaron Cois

      Glad you enjoyed it!

  • Taylerdurden

    Can you also please provide the information and code snippets on how to revert the messages received by the server to some other client ?
    I mean how to modify the above code , so that the message received by the server can be sent to some other client , just like a chat application?

    • http://www.codehenge.net Constantine Aaron Cois

      Good idea – I’ll write up a post on a simple chat server.

  • roballcon

    My thanks as well for an absolutely useful and professional tutorial.

  • cue2

    Aaron you’ve updated this guide for v0.7 however it appears that your client javascript code is missing and there is no link to download the tutorial files. for anybody who has seen the v0.6 tutorial this should be obvious but for those who see this page on its own it could be rather confusing.

  • Cameron

    Why did you leave all of the client side javascript out?

    • http://www.codehenge.net Constantine Aaron Cois

      Oops! I did some site updates that changed the code parsing, and somehow it must have been cut out. I have updated the post to put the client side JS back in. Thanks for the heads up!

45 queries in 3.202 seconds