Tuesday, June 7, 2016

Building a WebRTC Video Chat Application with PeerJS

This article was peer reviewed by Panayiotis Velisarakos and Ravi Kiran. Thanks to all of SitePoint's peer reviewers for making SitePoint content the best it can be!

With the advent of WebRTC and the increasing capacity of browsers to handle peer-to-peer communications in real-time, it's easier than ever to build real-time applications. In this tutorial we'll take a look at PeerJS and how it can make our lives easier when implementing WebRTC. Throughout this tutorial we'll be building a WebRTC video chat app with messaging features. If you need a bit of a background regarding WebRTC and peer-to-peer communication, I recommend reading The Dawn of WebRTC and Introduction to the getUserMedia API.

What Is PeerJS?

[author_more]

Before we move on, it's important that we understand the main tool that we'll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, video, and audio calls.

What it does is act as a wrapper around the browser's WebRTC implementation. As you might already know, browser vendors doesn't exactly agree on a single way of implementing different features which means that for every browser there's a different implementation for WebRTC. You as the developer would have to write different code for every browser that you plan to support. PeerJS acts as the wrapper for that code. The API that it exposes is easy to use and understand which makes it a really great candidate for implementing cross-browser WebRTC.

PeerServer

WebRTC isn't completely peer-to-peer. The reality is that there's always a server which bridges the connection between peers. Two or more devices can't just magically create a connection out of thin air. There are firewalls, routers and other roadblocks that can get in the way of peer-to-peer communication, which is where a server comes in.

PeerServer is the server-side component of PeerJS and allows two or more devices to connect together. You have two choices when it comes to PeerServer. You can either implement it your own by using the PeerJS server library or use the PeerServer Cloud Service.

So which is the right choice for your project?

If you want to get started quickly then PeerServer Cloud Service is for you. Just sign up to acquire an API key, which you can then use to connect to the PeerServer Cloud. The only downside to this option is that it doesn't really work in production. This is because you can only have 50 concurrent connections and the server isn't in HTTPS. The video call feature requires end-to-end encryption, which means that the PeerServer that you are connecting to should be in HTTPS as well.

If you're reading this tutorial to implement video or audio call features on your website then you will need the PeerJS server library. However, if you simply need a chat feature you can still use the PeerServer Cloud Service, provided your website doesn't exceed the concurrent connection limit.

As we move on through this tutorial I'll be showing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.

Building the WebRTC Video Chat App

Now it's time to get our hands dirty by building the app. First we're going to work with the client-side code and then we'll move over to the server side.

Please note that you can download the code for this tutorial from our GitHub repo. To run it, or to follow along at home, you will need to have Node and npm installed. If you're not familiar with these, or would like some help getting them installed, check out our previous tutorials:

The Client

In this section we'll be working primarily with the user-facing part of the app. This will have the following directory structure:

public
├── css
│   └── style.css
├── index.html
├── js
│   └── script.js
└── package.json

Dependencies

It also has the following client-side dependencies:

  • Picnic — a lightweight CSS framework.
  • jQuery — used for selecting elements on the page and event handling.
  • PeerJS — the client-side component of PeerJS.
  • Handlebars — a JavaScript templating library. We're going to use it for generating HTML for the messages.

You can install the libraries through npm. Create a package.json file in the root of the public directory and add the following:

{
  "name": "peer-messenger-client",
  "version": "0.0.1",
  "dependencies": {
    "jquery": "~2.1.4",
    "picnic": "~4.1.2",
    "peerjs": "~0.3.14",
    "handlebars": "~4.0.5"
  }
}

Execute npm install to install all the dependencies.

Mark-Up

The index.html file is reasonably self explanatory. You can find it here. I've added a couple of inline comments to highlight the important points.

Take a second to notice the Handlebars template for constructing the list of messages. This loops through all the messages in the messages array. For each iteration of the loop, we display the name of the sender and the actual message. Later on we'll take a look at how the data is being passed into this template.

<script id="messages-template" type="text/x-handlebars-template">
  
  <li>
    <span class="from">:</span> 
  </li>
  
</script>

Styling

The app only has minimal styling since most of the prettifying needs are already handled by Picnic. Our additional styles (in css/style.css) include some rules for positioning the elements, hiding things, and overriding the default one's provided by the browser.

Main App Script

The main JavaScript file (in js/script.js) is where all the logic of the app is contained. This includes such things as the login, initiating the call and capturing the users video. Let's take a look at the code.

We start off by declaring a couple of variables—the messages array, which will be used to store the messages that are sent by each of the peers, peer_id, which stores the ID of the remote peer, name, which stores the name of the current user and conn to store the current peer connection. We also compile the messages template using Handlebars and store the result in messages_template:

var messages = [];
var peer_id, name, conn;
var messages_template = Handlebars.compile($('#messages-template').html());

Next, we create a new PeerJS instance which accepts an object containing configuration options. Here, we're specifying the options host, port and the path, as this demo will use the PeerJS server library (I'll go into the configuration for the PeerServer Cloud Service later on). The debug option allows us to set the verbosity of the debug mode (3 being the highest) and the config option allows us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a STUN or TURN server. You don't really need to worry about the different terminologies for now. All you need to know is that these servers are used to make sure that the peer connection is successfully established. If you want to dive into to the specifics of WebRTC, I recommend you to read this HTML5Rocks article on WebRTC Basics and/or this Mozilla Hacks article on WebRTC acronyms. If you want to use another STUN or TURN server, you can look at this list of freely available STUN and TURN servers.

Continue reading %Building a WebRTC Video Chat Application with PeerJS%


by Wern Ancheta via SitePoint

Building a Study Guide App with Java Hashmap

These days, a physical dictionary is pretty old-fashioned. The idea of consulting a physical book to learn the meaning of a word or phrase makes no sense when a simple Google search will give you all the information you need.

But a dictionary provides a very useful metaphor for an important programming concept: key-value pairs. Dictionaries operate by linking a word (a "key") to its meaning (a "value"). The key-value pair is a fundamental data model in programming.

Most programming languages use hashes to ensure the uniqueness of keys and make storage and retrieval of values more efficient. A HashMap in Java puts all of that together to allow programmers to store key-value pairs by hashing their keys upon insertion and retrieval.

In this tutorial, we'll learn how to build a study guide program by storing Java concepts and their corresponding meanings in a HashMap to be retrieved when it’s time to study.

[author_more]

HashMap

Java maps make programs more efficient by storing key-value pairs in a single data structure. Alternatively, the same could be accomplished with two manually synced data structures -- one holding keys and the other holding values -- but this isn't the best approach to mapping keys to values; that's what a Map is for. The HashMap is arguably one of the most powerful of them all. All keys of the map must be of the same type, as must its values.

~~In the background, Java's HashMap class stores the pairs in arrays, but we don't have to worry much about the implementation because much of the heavy lifting is encapsulated and I think it's safe to trust that the Java developers know what they are doing.~~

The Map interface provides methods for putting pairs in the map, replacing the value of pairs, removing pairs by key, checking for the existence of a pair by key, and clearing the map. We'll make use of almost all of those functions today.

The Application

Our app will be a simple study guide app. We'll build our HashMap to store our concepts and use Java control-flow statements to loop until we have provided the correct meaning for each concept. Let's build!

Classes

We'll need two classes to run our study guide application. The first class will be our main class to run our program and the second will be another class to model the meaning of Java concepts and encapsulate a couple of fields and methods to simplify the study guide interface.

The first thing we need to do is create a new Java project with a main class. Once we have that set up, let's go ahead and build our Meaning class that will be used in our Main.

Continue reading %Building a Study Guide App with Java Hashmap%


by Lincoln Daniel via SitePoint

Five Ways to Hide Elements in CSS

There are multiple ways of hiding an element in CSS. You can hide it by setting opacity to 0, visibility to hidden, display to none or by setting extreme values for absolute positioning.
Have you ever wondered why we have so many techniques of hiding an element when they all seem to do the same thing? All of these methods actually differ slightly from each other and this difference dictates which one of them is to be used in a specific situation. This tutorial will cover the minor differences that you need to keep in mind when hiding an element using any of the methods above.

Opacity

The property opacity is meant to set an element's transparency. It was not designed to alter the bounding box of the element in any way. This means that setting the opacity to zero only hides the element visually. The element still occupies its position and affects the layout of the web page. It will also respond to user interaction as well.

.hide {
  opacity: 0;
}

If you intend to use the opacity property to hide the element from screen readers — unfortunately this is not possible. The element and all its content will be read by screen readers, just like all the other elements on the web page. In other words, the element behaves just the way it would have had it been opaque.

I should also mention that the opacity property can be animated and used to create some splendid effects. Any element with opacity less than 1 will also create a new stacking context.

Take a look at the following demo:

See the Pen Hiding elements with opacity by SitePoint (@SitePoint) on CodePen.

When you hover over the hidden second block, the element transitions smoothly from the state of complete transparency to being fully opaque. The block also has a cursor of pointer to show that it can be interacted with.

Visibility

The next property on our list is visibility. Setting it to hidden will hide our element. Just like the opacity property, the hidden element will still affect the layout of our web page. The only difference is that this time it will not capture any user interaction when hidden from the user. Additionally, the element will also be hidden from screen readers.

This property is also able to animate as long as the initial and final states have different values. This ensures that the transition between the states of visibility can be smooth instead of being abrupt.

.hide {
   visibility: hidden;
}

This demo shows how visibility is different from opacity:

See the Pen Hiding elements with visibility by SitePoint (@SitePoint) on CodePen.

Notice that the descendants of an element with visibility set to hidden can still be visible if their visibility property is explicitly set to visible. Try to hover just over the hidden element and not on the paragraph inside, you will see that your cursor does not change to a pointer. Moreover, if you try to click on the element, your clicks won't be registered either.

The <p> tag inside our <div> will still capture all the mouse events though. As soon as you hover over the text, the <div> itself becomes visible and starts registering events.

Display

The display property hides the element in the true sense of the word. Setting display to none makes sure that the box-model is not generated at all. Using this property, there is no empty space left behind when the element has been hidden. Not only that, but any direct user interaction won't be possible as long as display is set to none. Moreover, screen readers won't read the element's content either. It is as if the element does not exist.

All the descendants of our element will be hidden as well. This property cannot be animated so the transition between various states is always going to be abrupt.

Please note, the element is still accessible through the DOM. You will be able to manipulate it just like with any other element.

.hide {
   display: none;
}

Take a look at the CSS of this demo:

See the Pen Hiding elements with the display property by SitePoint (@SitePoint) on CodePen.

You will see that second block has a paragraph with its display property set to block but the paragraph is still invisible. This is one more difference between visibility: hidden and display: none. In the first case, any descendant which explicitly sets visibility to visible will become visible but that is not what happens with display. All the descendants are kept hidden irrespective of the value of their own display property.

Now, hover a few times over the first block in the demo. Done hovering? Click on this first block. This should make the second block visible. The count inside should now be a number other than zero. This is because the element, even though hidden from users can still be manipulated with JavaScript.

Continue reading %Five Ways to Hide Elements in CSS%


by Baljeet Rathi via SitePoint

Austrivia Quiz

This fun and informative web app quiz allows users to see how much they really know about Australia and Australian culture.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Website Design Durban

A graphic & web design agency in Durban, Kwazulu Natal, that aims to support both local as well as international clients. Be it branding, marketing or design & development – we have a solution.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

BeAwesome

BeAwesome is a Premium WordPress theme created for designers, illustrators, art directors and photographers that want to showcase their Behance projects in a fast, beautiful and interactive way.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Ash Flint

Portfolio of freelance graphic designer Ash Flint


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery