Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

October 07 2013

16:28

Node.js: Better Performance With Socket.IO and doT

If your site relies on data sent to clients, you can boost its performance using client-side templates and WebSockets. In this tutorial, I will show you how.


Introduction

We will begin by transforming a preexisting application to be faster and more durable under high traffic. I will show you how to locate pieces of code which could be modified to improve the app. Start by downloading the sample application that I prepared. It’s really simple, it displays random posts rendered on the server, but it will do just fine for this tutorial.


Step 1: Preparation

Unzip the app that you downloaded previously into a preferred folder or location and run it:

start_the_app

Now navigate to http://localhost:8080/ and take a look. You should see only a button. You’ll also need to be using a browser with developer tools, so you can see the size of the HTTP requests. Open the developer tools and go to the Network tab. Then, click the button a couple of times and take a look at the size of the /getpost request:

getpost_size

It’s only about 830 bytes right? Well, imagine that this site gets really popular and one million users want to see this post. It gets to about 830 megabytes. Per post! Not so small a number any more.


Step 2: Inspection

In this step I will show you how to find code that can be modified to boost up the app. In the previous step, you’ve found the request used to get the post. You will now have to find how it is served in the code. Open up the index.js file in your favorite code editor. Now go to the lines 16-20:

var postTemplate = dot(fs.readFileSync('./post.dot'));

app.get('/getpost', function (req, res) {
	res.end(postTemplate(posts[Math.floor(Math.random() * 3)]));
});

Here it is! First, the post’s template is compiled into the postTemplate variable. Then, on the /getpost GET request the template is served. Nothing fancy, just a classic approach to the problem. We’ll need to change this to improve its performance.


Step 3: Setting-Up Socket.IO

To begin the improvements, first, install Socket.IO. In your terminal type:

npm install socket.io

Wait for the command to complete. Require it in the code by adding the following line after all requires in index.js:

var sio = require('socket.io');

Now you will have to change the Express set-up, to work with Socket.IO. First, after the app definition, add this:

var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

server.listen(8080);

And remove the last line in this file:

app.listen(8080);

You need to do this because Socket.IO requires the HTTP Server to work, not the Express app.

Now, if you run the app you should see something like this in your terminal:

start_with_socketio

Step 4: Client-Side Template

To start boosting up the app you will need to save the compiled template on the client-side. Javascript files are cached, so it will be downloaded only once. To compile the template, go to http://olado.github.io/doT/index.html and scroll down to the Usage section. Because there will be no need to compile the template every time the user visits your site, you can just add the compiled function to the code. Open the post.dot file and paste its content into the Template field like this:

paste_the_template

Now copy the content of the field and paste it into the static/main.js file before all code in there. Change or remove the anonymous function name and assign it to the postTemplate variable like this:

var postTemplate = function (it) { ... }

Now go to the index.js file and remove unused lines, because you will not be compiling templates on the server-side any more:

var dot = require('dot').template;
var fs = require('fs');

...

var postTemplate = dot(fs.readFileSync('./post.dot'));

The post.dot file can also be deleted too.


Step 5: From AJAX to WebSockets

Instead of using AJAX to communicate with the server, we will now use WebSockets. It’s best to do this using Socket.IO, because the WebSocket API itself does not provide any fail-overs in case the user’s browser doesn’t support it. The server is already set-up, so now we will need to connect to it. First, add this in the head of the static/index.html file (before main.js):

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

Next, open the static/main.js file and after the template definition, add this code:

var socket = io.connect();

It will connect to the Socket.IO server (notice that you’ve added Socket.IO’s script to the page earlier). Since the server is on the same host as the client, you don’t need to provide any parameters to the function. Now, you need to add an event listener to the socket, so we know when the post arrives. Add this just after the previous line:

socket.on('getpost', function (data) {
	$('button').after(postTemplate(data));
});

As you can see, the callback looks the same as the success callback in jQuery’s $.ajax() method but it’s running the template function on the data first. Now, replace the $.ajax() call with this:

socket.emit('getpost');

This line will notify the server that the user wants to display a new post. Of course, in a real-world app, the server would send the posts when they are published.


Step 6: Sending the Posts

For now, the client can connect to the server and request a post, but the server will not send anything yet. You need the server socket to listen to the getpost event and respond with a random post. Go to the index.js file and change it to this:

app.get('/getpost', function (req, res) {
	res.end(postTemplate(posts[Math.floor(Math.random() * 3)]));
});

To this:

io.sockets.on('connection', function (socket) {
	socket.on('getpost', function () {
		socket.emit('getpost', posts[Math.floor(Math.random() * 3)]);
	});
});

This will make the server attach the getpost handler to every client that connects to it and respond him with a random post. Now you can run the app again and try it out. Then go to the developer tools in your browser again, go to the Network tab, filter it out so you can only see WebSockets and click on the one that is visible there. You should see the data sent between the browser and the server, and notice that it is much smaller then it was with the server-side template and AJAX (the length is in bytes):

getpost_ws_size

Conclusion

As you can see, using WebSockets and client-side templates can (and probably will) improve the performance and durability of your app. I’m sure there are plenty of sites that could be boosted with this technique and I hope that you will use it to provide a better user experience, both for your mobile and desktop users.

September 04 2013

18:44

Using Node.js and Websockets to Build a Chat Service

Node.js and Websockets are the perfect combination to write very fast, lag free applications which can send data to a huge number of clients. So why don’t we start learning about these two topics by building a chat service! We will see how to install Node.js packages, serve a static page to the client with a basic web-server, and configure Socket.io to communicate with the client.


Why Choose Node.js and Socket.io?

1

So why use this combo?

There are a lot of platforms which can run a chat application, but by choosing Node.js we don’t have to learn a completely different language, it’s just JavaScript, but server-side.

Node.js is a platform built on Chrome’s JavaScript runtime to make building applications in JavaScript that run on the server, easy. Node.js uses an event-driven, non-blocking I/O model, which makes it perfect for building real time apps.

More and more Node.js applications are being written with real-time communication in mind. A famous example is BrowserQuest from Mozilla, an MMORPG written entirely in Node.js whose source code has been released on Github.

Node.js comes with a built-in package manager : npm. We will use it to install packages that will help speed up our application development process.

We’ll be using three packages for this tutorial: Jade, Express, and Socket.io.

Socket.io: the Node.js Websockets Plugin

The main feature of our application is the real-time communication between the client and the server.

HTML5 introduces Websockets, but it is far away from being supported by all users, so we need a backup solution.

Socket.io is our backup solution : it will test Websocket compatibility and if it’s not supported it will use Adobe Flash, AJAX, or an iFrame.

Finally, it supports a very large set of browsers:

  • Internet Explorer 5.5+
  • Safari 3+
  • Google Chrome 4+
  • Firefox 3+
  • Opera 10.61+
  • iPhone Safari
  • iPad Safari
  • Android WebKit
  • WebOs WebKit

It also offers very easy functions to communicate between the server and the client, on both sides.

Let’s start by installing the three packages we will need.


Installing Our Dependencies

Npm allows us to install packages very fast, using one line, so first go to your directory and have npm download the needed packages:

npm install express jade socket.io
2

Now we can start building our server-side controller to serve the main page.

We are going to save all the server-side code into a "server.js" file which will be executed by Node.js.


Serving a Single Static Page

7

To serve our static page we will use Express, a package which simplifies the whole server-side page send process.

So let’s include this package into our project and start the server:

var express = require('express'), app = express.createServer();

Next, we need to configure Express to serve the page from the repertory views with the Jade templating engine that we installed earlier.

Express uses a layout file by default, but we don’t need it because we will only serve one page, so instead, we will disable it.

Express can also serve a static repertory to the client like a classic web server, so we will send a "public" folder which will contain all our JavaScript, CSS and image files.

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.configure(function() {
	app.use(express.static(__dirname + '/public'));
});

Next, let’s create two folders inside our project folder named "public" and "views".

Now we just need to configure Express to serve a "home.jade" file, which we will create in a moment, and then set Express to listen for a specific port.

I will use port 3000 but you can use whatever you’d prefer.

app.get('/', function(req, res){
  res.render('home.jade');
});
app.listen(3000);

Creating the Jade Template Page

3

Node.js uses templating engines to serve webpages. It’s useful to send dynamic pages and to build them faster.

In this tutorial, we will use Jade. Its syntax is very clear and it supports everything we need.

“Jade is a high performance templating engine heavily influenced by Haml and implemented with JavaScript for Node.”

Now, I’m not going to go over Jade in detail, if you need more help, you can find very well written documentation on its Github repo.

Jade Configuration

We installed Jade earlier, but we need to include it in our server.js file like we did for Express.

By convention, we include our libraries at the top of our file to use them later, without having to check if they are already included. So place the following code at the top of your "server.js" file :

var jade = require('jade');

And that completes our Jade configuration. Express is already setup to use Jade with our view files, to send an HTML response, we just need to create that file.

Creating Our Home Page

If we start our server now it will crash because we’re requesting our app to send a page which doesn’t exist yet.

We’re not going to create a full featured page, just something basic that has a title, a container for the messages, a text area, a send button, and a user counter.

Go ahead and create a "home.jade" page inside the "views" folder with the following code:

doctype 5
html
	head
		title Chat
		script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
		script(src="/socket.io/socket.io.js")
		script(src="script.js")
	body
		div.container
			header
				h1 A Chat application with Node.js and Socket.io
			input(type='text')#pseudoInput
			button#pseudoSet Set Pseudo
			div#chatEntries
			div#chatControls
				input(type='text')#messageInput
				button#submit Send

“Jade is all about indentation”

The Jade language is all about indentation. As you can see, we don’t need to close our containers, just indenting the children of the parent container is enough.

We also use a period "." and a pound sign "#" to indicate the class or ID of the element, just like in a CSS file.

We also link in three scripts at the top of the file. The first is jQuery from Google CDN, next we have the Socket.io script which is served automatically by the package, and finally a "script.js" file which will keep all of our custom JS functions.


The Socket.io Server-Side Configuration

6

Socket.io is event based, just like Node. It aims to make real-time apps possible in every browser and mobile device, blurring the lines between these different transport mechanisms. It’s care-free, real-time, and 100% JavaScript.

Like the other modules, we need to include it in our server.js file. We will also chain on our express server to listen for connections from the same address and port.

var io = require('socket.io').listen(app);

The first event we will use is the connection event. It is fired when a client tries to connect to the server; Socket.io creates a new socket that we will use to receive or send messages to the client.

Let’s start by initializing the connection:

io.sockets.on('connection', function (socket) {
	//our other events...
});

This function takes two arguments, the first one is the event and the second is the callback function, with the socket object.

Using code like this, we can create new events on the client and on the server with Socket.io. We will set the "pseudo" event and the "message" event next.

To do this, it’s really simple, we just use the same syntax, but this time with our socket object and not with the "io.sockets" (with an “s”) object. This allows us to communicate specifically with one client.

So inside our connection function, let’s add in the "pseudo" event code.

socket.on('setPseudo', function (data) {
	socket.set('pseudo', data);
});

The callback function takes one argument, this is the data from the client and in our case it contains the pseudo. With the "set" function, we assign a variable to the socket. The first argument is the name of this variable and the second is the value.

Next, we need to add in the code for the "message" event. It will get the user’s pseudo, broadcast an array to all clients which contains the message we received as well as the user’s pseudo and log it into our console.

socket.on('message', function (message) {
	socket.get('pseudo', function (error, name) {
		var data = { 'message' : message, pseudo : name };
		socket.broadcast.emit('message', data);
		console.log("user " + name + " send this : " + message);
	})
});

This completes our server-side configuration. If you’d like, you can go ahead and use other events to add new features to the chat.

The nice thing about Socket.io is that we don’t have to worry about handling client disconnections. When it disconnects, Socket.io will no longer receive responses to “heartbeat” messages and will deactivate the session associated with the client. If it was just a temporary disconnection, the client will reconnect and continue with the session.


The Socket.io Client-Side Configuration

Now that our server is configured to manage messages, we need a client to send them.

The client-side of Socket.io is almost the same as the server-side. It also works with custom events and we will create the same ones as on the server.

So first, create a "script.js" file inside the public folder. We will store all of our functions inside of it.

We first need to start the socket.io connection between the client and the server. It will be stored in a variable, which we will use later to send or receive data. When the connection is not passed any arguments, it will automatically connect to the server which will serve the page.

var socket = io.connect();

Next, let’s create some helper functions that we will need later. The first is a simple function to add a message to the screen with the user’s pseudo.

function addMessage(msg, pseudo) {
	$("#chatEntries").append('<div class="message"><p>' + pseudo + ' : ' + msg + '</p></div>');
}

This helper uses the append function from jQuery to add a div at the end of the #chatEntries div.

Now we are going to write a function that we can call when we want to send a new message.

function sentMessage() {
	if ($('#messageInput').val() != "") 
	{
		socket.emit('message', $('#messageInput').val());
		addMessage($('#messageInput').val(), "Me", new Date().toISOString(), true);
		$('#messageInput').val('');
	}
}

First, we verify that our textarea is not empty, then we send a packet named "message" to the server which contains the message text, we print it on the screen with our "addMessage" function, and finally we remove all the text from the textarea.

Now, when the client opens the page, we need to set the user’s pseudo first. This function will send the pseudo to the server and show the textarea and the submit button.

function setPseudo() {
	if ($("#pseudoInput").val() != "")
	{
		socket.emit('setPseudo', $("#pseudoInput").val());
		$('#chatControls').show();
		$('#pseudoInput').hide();
		$('#pseudoSet').hide();
	}
}

Additionally, we hide the pseudo setting controls when it’s sent to the server.

Now just like we did on the server-side, we need to make sure we can receive incoming messages and this time we’ll print them on the screen. We’ll use the same syntax but this time we call the "addMessage" function.

socket.on('message', function(data) {
	addMessage(data['message'], data['pseudo']);
});

Just like with our server configuration, the packet that is sent to the client is an array containing the message and the pseudo. So we just call our "addMessage" function passing in the message and the pseudo, which we extract from the received data packet.

Now we just need to add the initialization function which is fired once the page is fully loaded.

$(function() {
	$("#chatControls").hide();
	$("#pseudoSet").click(function() {setPseudo()});
	$("#submit").click(function() {sentMessage();});
});

First, we hide the chat controls before the pseudo is set and then we set two click listeners which listen for clicks on our two submit buttons. The first is for the pseudo and the second is for the messages.

And that wraps up our client-side script.


Conclusion

We now have a working chat service. To start it, just run the following command :

node server.js

In your terminal you should get a message from Socket.io saying that the server is started. To see your page go to 127.0.0.1:3000 (or whichever port you chose previously).

4

The design is very basic, but you could easily add in a stylesheet with CSS3 transitions for incoming messages, HTML5 sounds, or Bootstrap from Twitter.

As you can see, the server and client scripts are fairly similar: this is the power of Node.js. You can build an application without having to write the code twice.

Finally, you may have noticed that it only took 25 lines of code inside our server.js file to create a functional chat app, with amazing performance. It is very short, but it also works very well.

Now if you’re interested, I have created a better chat service application, with a good looking design, along with some additional features. It is hosted on Nodester and the source code is on Github.

Here is a preview of it.

5

Thanks for reading.

Sponsored post
soup-sponsored
04:52

April 18 2013

17:30

Mozilla Labs TowTruck: Brand-new Real-Time Collaboration Tool Tested


  
towtruck-logo

Mozilla Labs achieves amazing things. And this is more of an under- than an overstatement. The latest sprout from Mozilla's garden, interestingly named TowTruck, makes no exception and promises a lot. TowTruck lets you integrate collaboration features into any website with a mere two lines of code. Once done, people can communicate, collaborate, create together right inside any website. They can even talk to each other via WebRTC. Noupe took a closer look...

July 28 2010

14:54

Start Using HTML5 WebSockets Today


One of the cool new features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we’ll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.


What are WebSockets?

WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. At the moment, it’s still being standardized by the W3C; however, the latest versions of Chrome and Safari have support for WebSockets.


What do WebSockets Replace?

Websockets can replace long-polling. This is an interesting concept; the client sends a request to the server – now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent – the client next receives this, and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long-polling isn’t really a piece of fancy technology: it’s also possible for a request to time-out, and thus a new connection will be needed anyway.

Many Ajax applications makes use of the above – this can often be attributed to poor resource utilization.

Wouldn’t it be great if the server could wake up one morning and send its data to clients who are willing to listen without some sort of pre established connection? Welcome to the world of PUSH technology!


Step 1: Get the WebSocket Server

This tutorial will focus more on the client building rather than server implementation.

I’m using XAMPP on Windows 7 to run the PHP server locally. Grab a copy of phpwebsockets which is a WebSocket server in PHP. (Note: I experienced some problems with this version, I made some changes to it and will including it in the source files) There are various WebSocket implementations; if one doesn’t work, you can try another or just continue with the tutorial.

Start the Apache server


Step 2: Change URLs and Ports

Change the server according to your setup, for example in setup.class.php:

public function __construct($host='localhost',$port=8000,$max=100)
{
	$this->createSocket($host,$port);
}

Browse through the files and make changes where appropriate.


Step 3: Start Building the Client

Lets get a basic template up; this is my client.php file:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<title>WebSockets Client</title>

</head>
<body>
<div id="wrapper">

    <div id="container">

        <h1>WebSockets Client</h1>

        <div id="chatLog">

        </div><!-- #chatLog -->
        <p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>

        <input id="text" type="text" />
        <button id="disconnect">Disconnect</button>

    </div><!-- #container -->

</div>
</body>
</html>​

So in this code we’re creating a simple template: we have a box for the chat log, an input box, and one disconnect button.


Step 4: Add Some CSS

Nothing fancy, just space some elements out.

body {
	font-family:Arial, Helvetica, sans-serif;
}
#container{
	border:5px solid grey;
	width:800px;
	margin:0 auto;
	padding:10px;
}
#chatLog{
	padding:5px;
	border:1px solid black;
}
#chatLog p {
	margin:0;
}
.event {
	color:#999;
}
.warning{
	font-weight:bold;
	color:#CCC;
}

Step 5: WebSocket Events

First, let’s try and understand the idea of WebSocket events.

The Events

We’ll be using three events:

  • onopen: When a socket has opened
  • onmessage: When a message has been received
  • onclose: When a socket has been closed

But how can we implement this?

First create a WebSocket object

var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");

And checking for events is as simple as:

socket.onopen = function(){
	alert("Socket has been opened!");
}

But what about when we receive a message?

socket.onmessage = function(msg){
	alert(msg);	//Awesome!
}

However, let’s avoid using alert boxes, and actually integrate what we’ve learned into the client page.


Step 6: JavaScript

Ok, so let’s get started. First we put our code in jQuery’s document ready function, then we check whether the user has a WebSockets-enabled browser. If they do not, we append a link to Chrome in the HTML.

$(document).ready(function() {
	if(!("WebSocket" in window)){
		$('#chatLog, input, button, #examples').fadeOut("fast");
		$('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
	}else{

	//The user has WebSockets

	connect();

	function connect(){
    	//the connect function code is below

	}
});

As you can see, if the user has WebSockets then we call a connect() function. This is the core of the functionality: we’ll start with the open, close and receive events.

We’ll define the URL of our server

var socket;
var host = "ws://localhost:8000/socket/server/startDaemon.php";

Wait, where’s the http in that URL? Oh right, it’s a WebSocket URL, so it’s using a different protocol. Here’s a breakdown of the pieces of our URL:

Let’s continue with our connect() function. We will put our code within a try/catch block; so if something goes wrong, we can let the user know. We create a new WebSocket, and pass the message to a message function which I’ll explain later. We create our onopen, onmessage and onclose functions. Note that we also show the user the socket status; this is not necessary, but I’m including it here as it can be helpful for debugging.

  • CONNECTING = 0
  • OPEN = 1
  • CLOSED = 2
function connect(){
    try{

	var socket;
	var host = "ws://localhost:8000/socket/server/startDaemon.php";
    var socket = new WebSocket(host);

        message('<p class="event">Socket Status: '+socket.readyState);

        socket.onopen = function(){
       		 message('<p class="event">Socket Status: '+socket.readyState+' (open)');
        }

        socket.onmessage = function(msg){
       		 message('<p class="message">Received: '+msg.data);
        }

        socket.onclose = function(){
       		 message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
        }			

    } catch(exception){
   		 message('<p>Error'+exception);
    }
}

The message() function is fairly simple, it takes in some text that we want to show the user and appends it to the chatLog. We create the appropriate class for paragraph tags in the socket event functions which is why there is only one closing paragraph tag in the message function.

function message(msg){
	$('#chatLog').append(msg+'</p>');
}

So Far…

If you’ve been following up to this point, well done! We’ve managed to create a basic HTML/CSS template, create and establish a WebSocket connection and keep the user updated as progress was made with the connection.


Step 7: Sending Data

Now rather than having a submit button, we can detect when the user presses return on their keyboard, and run the send function. The ’13′ you see below is the ASCII key for the enter button.

$('#text').keypress(function(event) {
    if (event.keyCode == '13') {
   		send();
    }
});

And here’s the send() function:

function send(){

    var text = $('#text').val();
    if(text==""){
        message('<p class="warning">Please enter a message');
        return ;
    }
    try{
        socket.send(text);
        message('<p class="event">Sent: '+text)
    } catch(exception){
   	message('<p class="warning"> Error:' + exception);
    }

    $('#text').val("");

}

Remember what you see above may be a chunky bit of code, but in reality, the code we really need is:

socket.send(); //Thanks JavaScript

The extra code is doing a number of things: detecting if the user didn’t enter anything but still hit return, clearing the input box, and calling the message functions.


Step 8: Closing the Socket

Closing the socket is fairly straightforward: attach a click handler to our disconnect button and we’re done!

$('#disconnect').click(function(){
	socket.close();
});

The Completed JavaScript

$(document).ready(function() {

  if(!("WebSocket" in window)){
  $('#chatLog, input, button, #examples').fadeOut("fast");
  $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
  }else{
      //The user has WebSockets

      connect();

      function connect(){
          var socket;
          var host = "ws://localhost:8000/socket/server/startDaemon.php";

          try{
              var socket = new WebSocket(host);

              message('<p class="event">Socket Status: '+socket.readyState);

              socket.onopen = function(){
             	 message('<p class="event">Socket Status: '+socket.readyState+' (open)');
              }

              socket.onmessage = function(msg){
             	 message('<p class="message">Received: '+msg.data);
              }

              socket.onclose = function(){
              	message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
              }			

          } catch(exception){
             message('<p>Error'+exception);
          }

          function send(){
              var text = $('#text').val();

              if(text==""){
                  message('<p class="warning">Please enter a message');
                  return ;
              }
              try{
                  socket.send(text);
                  message('<p class="event">Sent: '+text)

              } catch(exception){
                 message('<p class="warning">');
              }
              $('#text').val("");
          }

          function message(msg){
            $('#chatLog').append(msg+'</p>');
          }

          $('#text').keypress(function(event) {
              if (event.keyCode == '13') {
                send();
              }
          });	

          $('#disconnect').click(function(){
             socket.close();
          });

      }//End connect

  }//End else

});

Step 9: Run the WebSocket Server

We will need command line access. Luckily, XAMPP has a handy shell option. Click ‘Shell’ on the XAMPP control panel, and type in:

php -q path\to\server.php

You have now started a WebSocket server!


Finished

When the page loads, a WebSocket connection will attempt to be established (try editing the code so the user has connect/disconnect option). Then, the user can enter messages and receive messages from the server.


That’s it!

Thanks for reading; I hope you enjoyed this tutorial! Remember, as exciting as WebSockets may be, things may change. You can refer here to keep up to date on the W3C WebSocket API.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...