<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Never Settle]]></title><description><![CDATA[Thoughts, stories and ideas.]]></description><link>http://nelsonzheng.com/</link><generator>Ghost 0.10</generator><lastBuildDate>Mon, 27 Apr 2026 10:54:35 GMT</lastBuildDate><atom:link href="http://nelsonzheng.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Building a chat application with SocketCluster]]></title><description><![CDATA[In this guide, we will build a basic chat application with Node.js and SocketCluster.io]]></description><link>http://nelsonzheng.com/building-a-chat-application-with-socketcluster/</link><guid isPermaLink="false">168a8566-e67a-47cc-bb16-5c488793c827</guid><category><![CDATA[SocketCluster]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Nelson Zheng]]></dc:creator><pubDate>Thu, 30 Apr 2015 12:06:00 GMT</pubDate><media:content url="http://nelsonzheng.com/content/images/2015/04/photo-1413708617479-50918bc877eb-1920-tingypng.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://nelsonzheng.com/content/images/2015/04/photo-1413708617479-50918bc877eb-1920-tingypng.jpg" alt="Building a chat application with SocketCluster"><p>In this guide, we are going to create a basic web chat application with <a href="http://nodejs.org/">Node.js</a> and the <a href="http://socketcluster.io/">SocketCluster.io</a> module. The chat application will allow our users to create chat rooms that they can share with their friends. </p>

<p>This guide requires zero prior knowledge to <a href="http://nodejs.org/">Node.js</a> or <a href="http://socketcluster.io/">SocketCluster.io</a> so it is ideal for users of all levels of experience.</p>

<h1 id="introduction">Introduction</h1>

<p>In order for our chat applications to work, messages sent by any individual user must be relayed to all other users. Traditionally, web chat rooms built on PHP have struggled with bidirectional real-time communications. </p>

<p>This problem is solved by using <a href="https://developer.mozilla.org/en/docs/WebSockets">WebSockets</a>, a technology that makes it possible to maintain an interactive session between the client and the server.</p>

<p>Rather than polling the servers for any new messages like we used to do before, we are now able to <em>push</em> the message to other all users once it has been received by the server. </p>

<h1 id="setupourenvironment">Setup our environment</h1>

<p>The first thing to do is to install <a href="https://nodejs.org/">Node.js</a> on your system. You can follow one of <a href="https://github.com/joyent/node/wiki/installation">these</a> official guides on how to do so depending on your operating system.</p>

<p>Installing Node.js will also come with its package manager called <a href="http://nelsonzheng.com/building-a-chat-application-with-socketcluster/npmjs.org">npm</a>. We will use <code>npm install</code> to install SocketCluster.</p>

<p><code>npm install -g socketcluster</code></p>

<p>Depending on your system, you may need to run the command with super user privileges</p>

<p><code>sudo npm install -g socketcluster</code> </p>

<h1 id="creatingtheapplication">Creating the application</h1>

<p>Once we have SocketCluster installed we can now use it to create our application. Browse to the location where you want to have your application installed, and run the following command in your terminal. I've chosen to install this in my home directory and I've called my chat application <code>sc-chat</code>.</p>

<p><code>socketcluster create sc-chat</code></p>

<h2 id="testingtheserver">Testing the server</h2>

<p>If we run <code>node server</code> we should see the following: <br>
<img src="http://nelsonzheng.com/content/images/2015/04/chat1.png" alt="Building a chat application with SocketCluster"></p>

<p>And if we browse to <code>http://localhost:8000</code> we should see this: <br>
<img src="http://nelsonzheng.com/content/images/2015/04/chat2.png" alt="Building a chat application with SocketCluster"></p>

<p>Yay! We have our basic server running and we can see the default application page!</p>

<h2 id="editingthehtml">Editing the HTML</h2>

<p>So far, we've been able to run our server and have it deliver the default page. Let's now go ahead and edit that page to make our chat application. Open up the <code>public/index.html</code> in your favourite text editor and replace its contents with this:</p>

<pre><code>&lt;!DOCTYPE html&gt;  
&lt;html&gt;  
  &lt;head&gt;
    &lt;title&gt;SocketCluster Chat Application&lt;/title&gt;
    &lt;link href='//fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet' type='text/css'&gt;
    &lt;link rel="stylesheet" type="text/css" href="css/style.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class="container"&gt;
      &lt;div class="messages"&gt;
        &lt;ul id="messages-list"&gt;&lt;/ul&gt;
      &lt;/div&gt;
      &lt;div class="actions"&gt;
        &lt;form&gt;
          &lt;input id="message" autocomplete="off" placeholder="Type a message..."&gt;
          &lt;button&gt;Send&lt;/button&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;  
</code></pre>

<h2 id="addingsomecss">Adding some CSS</h2>

<p>Create the <code>css</code> directory inside your application and save the following CSS file inside:</p>

<pre><code>body {
  margin: 0;
  padding: 0;
  color: #666666;
  font-weight: 300;
  font-family: 'Roboto';
  background-color: #F9F9F9;
}
a {
  font-weight: 300;
  color: #72B963;
}
.container {
  margin: 10vh 10vw ;
  position: relative;
  width: 80vw;
  background-color: #FFFFFF;
  border: 1px solid #EEEEEE;
  height: 80vh;
}
.container ul {
  margin: 0;
  padding: 0;
}
.container ul&gt;li {
  list-style: none;
  padding: 20px;
  border-bottom: 1px solid #EEEEEE;
}
.container ul&gt;li:nth-child(odd) { 
  background: #F6F5F6; 
}
.messages {
  height: 75vh;
  overflow-y: scroll;
}
.actions {
  position: absolute;
  bottom: 0;
  background-color: #CCCCCC;
  width: 100%;
  border-top: 1px solid #EEEEEE;
}
.actions input {
  border: 0;
  margin: 0;
  font-size: 1em;
  padding: 1.5vh 1vw;
  width: 68vw;
  float: left;
}
.actions button {
  border: 0;
  margin: 0;
  width: 10vw;
  text-align: center;
  font-size: 1em;
  padding: 1.5vh 1vw;
  float: left;
  background-color: #2ecc71;
  color: #FFFFFF;
}
</code></pre>

<p>Refresh the page and it should look like this: <br>
<img src="http://nelsonzheng.com/content/images/2015/04/chat3.png" alt="Building a chat application with SocketCluster"></p>

<h2 id="socketclusteraction">SocketCluster action</h2>

<p>Let's add some code to our server's <code>worker.js</code> so that we can see when someone has connected to the server:  </p>

<pre><code>scServer.on('connection', function (socket) {  
  console.log('User connected');
  socket.on('disconnect', function () {
    console.log('User disconnected');
  });
});
</code></pre>

<p>Now inside <code>index.html</code> we can add the Javascript to trigger this event. Add the following code right before the <code>&lt;/body&gt;</code> tag.  </p>

<pre><code>&lt;script type="text/javascript" src="/socketcluster.js"&gt;&lt;/script&gt;  
&lt;script type="text/javascript"&gt;  
  var socket = socketCluster.connect();

  socket.on('error', function (err) {
    throw 'Socket error - ' + err; 
  });

  socket.on('connect', function () {
    console.log('Connected to server');
  });
&lt;/script&gt;  
</code></pre>

<p>Now if we restart the server by pressing <code>Ctrl+C</code> on the terminal running the server and re-running <code>node server</code>, and refreshing the page we will see this: <br>
<img src="http://nelsonzheng.com/content/images/2015/04/chat4.png" alt="Building a chat application with SocketCluster"></p>

<p>Also notice that in our browsers console, it prints <code>Connected to server</code> once a connection has been established. <br>
<img src="http://nelsonzheng.com/content/images/2015/04/chat5.png" alt="Building a chat application with SocketCluster"></p>

<h2 id="emittingevents">Emitting events</h2>

<p>Now let's introduce some event emissions so that when the user types a message, the server will receive a <code>chat</code> event. Let's update the javascript above the <code>&lt;/body&gt;</code> to this:</p>

<pre><code>&lt;script type="text/javascript" src="/socketcluster.js"&gt;&lt;/script&gt;  
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt;  
&lt;script type="text/javascript"&gt;  
  var socket = socketCluster.connect();

  socket.on('error', function (err) {
    throw 'Socket error - ' + err;
  });

  socket.on('connect', function () {
    console.log('Connected to server');
  });

  $('form').submit(function(){
    if($('#message').val() != '') {
      socket.emit('chat', $('#message').val());
    } 

    $('#message').val('')

    return false;
  });
&lt;/script&gt;  
</code></pre>

<p>And we will print the messages we receive on the server, for now.</p>

<pre><code>scServer.on('connection', function (socket) {

  console.log('User connected');

  socket.on('chat', function (data) {
    console.log('Chat:', data);
  });

  socket.on('disconnect', function () {
    console.log('User disconnected');
  });
});
</code></pre>

<p><img src="http://nelsonzheng.com/content/images/2015/04/out.gif" alt="Building a chat application with SocketCluster"></p>

<h2 id="broadcasting">Broadcasting</h2>

<p>Now that we are receiving the chat messages on the server, it is time to broadcast it to all our clients. We do this by adding <code>scServer.global.publish('yell', data);</code>the following line to our chat event.</p>

<pre><code>scServer.on('connection', function (socket) {

  console.log('User connected');

  socket.on('chat', function (data) {
    scServer.global.publish('yell', data);
    console.log('Chat:', data);
  });

  socket.on('disconnect', function () {
    console.log('User disconnected');
  });
});
</code></pre>

<p>And listening for this <code>yell</code> event on the client by adding the following before our <code>&lt;/body&gt;</code> tag:  </p>

<pre><code>&lt;script type="text/javascript" src="/socketcluster.js"&gt;&lt;/script&gt;  
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt;  
&lt;script type="text/javascript"&gt;  
  var socket = socketCluster.connect();

  socket.on('error', function (err) {
    throw 'Socket error - ' + err;
  });

  socket.on('connect', function () {
    console.log('Connected to server');
  });

  $('form').submit(function(){
    if($('#message').val() != '') {
      socket.emit('chat', $('#message').val());
    } 

    $('#message').val('')
    return false;
  });

  var chatChannel = socket.subscribe('yell');

  chatChannel.on('subscribeFail', function(err) {  
    console.log('Failed to subscribe to Yell channel due to error: ' + err);
  });

  chatChannel.watch(function (data) {  
    $('#messages-list').append($('&lt;li&gt;').text(data));
  });
&lt;/script&gt;  
</code></pre>

<p>This will listen for any <code>yell</code> events and then take the message and insert it to our messages list.</p>

<p>And that's it! Messages sent from any one client will be broadcasted to all our clients and displayed. <br>
<img src="http://nelsonzheng.com/content/images/2015/04/out-1.gif" alt="Building a chat application with SocketCluster"></p>

<h3 id="getthisongithub">Get this on GitHub</h3>

<p><a href="https://github.com/nelsonzheng/sc-chat">https://github.com/nelsonzheng/sc-chat</a></p>]]></content:encoded></item></channel></rss>