Web Technologies

Introduction to Web Socket and Server Concepts

ZHdK, BA Interaction Desgin | Bits & Atoms II

by Andrés Villa Torres

What is Web Socket?

A WS is a communication protocol that allows to bi-directionally transfer data through the peer-processes over the internet.

The "peers" are computer systems which are connected to each other via the Internet, commonly through a server.

This protocol enables interaction between one or more web browsers (or other client applications) and a web server facilitating real-time data transfer from and to the server as long as the connections between the clients and the server are persistent.

A WS is a standard bidirectional TCP (transmission control protocol) socket between the client and the server. The socket starts out as a HTTP connection and then "upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.

More Information Source

WS != HTTP

WS provides full-duplex communication channels over a single TCP connection. HTTP provides half-duplex communication.

Information exchange mode of WS is bidirectional, hence a server can push information to the client, which is not allowed directly through HTTP.

WS != HTTP

Practical Applications

A WS is useful for building applications or networked services that require constant communication, such as chat applications, multi-user online platforms, real-time GPS and sensor-data tracking, bidirectional video streaming, p2p communication, etc.

Examples

Chat A

Chat B

White Board

Hands on

1 | Install and test node.js

2 | Install and test httpserver

3 | Download socket.io and run demos

4 | Write a GPS tracker with socket.io

5 | Enable global access to a local server

1 | install and test node.js

An open-source, cross-platform, JavaScript runtime environment that executes code outside of a web browser. It lets developers use JS to write command-line tools and scripts to produce dynamic web page content before the page is sent to the viewer's web browser.

Installation Instructions

Files for myFirstNode.js inside WS_MATERIALS/NODE_TEST/

2 | install and test httpserver

A command line HTTP server tool for serving up local files, similar to python -mSimpleHTTPServer

Installation Instructions

Files for HTTPServer Test inside WS_MATERIALS/HTTPSERVER_TEST/

3 | Download and test socket.io

Run Demos "Chat" and "Whiteboard" Locally

NPM is a package manager for NODE. For running the SOCKET io examples, some other modules are needed.

Usually packages like socket.io contain all the modules needed. These modules can be installed with NPM inside the specific example folder and through the terminal command 'npm i'.

Link to download socket.io

Two Steps Back

What is node.js ?

What is the TERMINAL?

node js (again)

Terminal: shortly explained

In macOS a terminal emulator is the application that provides text-based access to the operating system, in contrast to the mostly graphical nature of the user experience of macOS, by providing a command line interface to the operating system

Terminal > Basic Commands

A command line interface is basically about running commands through text-based input


cd PATH		>	change directory
cd..		>	move up to the parent directory
cd../..		>	Move up two levels
ls 		>	List content
mkdir PATH	>	makes directory 
rm -r 		> 	removes files and folder recursively
df -h		>	Calculate your system's free disk space
					
					

Keyboard input : command + '.' > stops all processes running

4 | Write a GPS "Hack" Tracker

4.1 | setup basic file tree

4.2 | create package.json via 'npm init'

4.3 | install express dependencies via 'npm install express --save'

4.4 | install socketio dep via 'npm install socket.io --save'

4.5 | fill in code inside your file tree

4.1 Setup File Tree

4.2 Create package.json

4.3 Express Dependencies

4.4 socket.io Dependencies

How the File Tree should look

4.5 Fill in the code

appRoot/index.js

						
const express = require('express');
const socket = require('socket.io');


// App Setup
const app = express();
const port = 8080;

const server = app.listen(port, function(){
	console.log('listening to requests on port 8080');
});

// Static Files
app.use(express.static('public'));


// Socket Setup
const io = socket(server);


// Function that Responds upon "message" Connection
io.on('connection',function(socket){
	
	var socketID = socket.id;
	console.log('new client connected id: ' , socketID);

	// Emit Connected message to all the sockets
	io.sockets.emit('connected',{
		id : socketID
	});

	// Handle the Location Events
	socket.on('location',function(data){

		io.sockets.emit('location',data);
		console.log(data);
	});


	//Upon disconnect
	socket.on('disconnect',function(){

		console.log('the id :' , socketID , 'has disconnected');
	})

});
						
					

appRoot/public/main.js

						
var latitude,longitude,altitude;
var hasTheIntervalBeenSet = false;


document.addEventListener('DOMContentLoaded', function(){
	// Make Connection
	var socket = io();



	var btn = document.getElementById('send'),
	output = document.getElementById('output'),
	debug = document.getElementById('debug-info');

	// Emit Event Location after clicking Button
	btn.addEventListener('click',geoLocateMe);

	// Listen for another client connection

	socket.on('connected',function(data){

		debug.innerHTML += '

new client connected id: ' + data.id+ '

'; }); //Listen for other's Location Events socket.on('location', function(data){ output.innerHTML += '

' +data.lat + ","+ data.long + "," + data.alt + " , id : " + data.id +'

'; }); //Function GeoLocate function geoLocateMe(){ function success(position){ // do something in case geolaction succeeds if(!hasTheIntervalBeenSet){ setInterval(geoLocateMe,500); hasTheIntervalBeenSet=true; } latitude = position.coords.latitude; longitude = position.coords.longitude; altitude = position.coords.altitude; socket.emit('location', { lat: latitude, long: longitude, alt: altitude, id: socket.id }); } function error(){ // do something in case geolocation fails } if(!navigator){ // do something if not navigator available }else{ // try to get the location navigator.geolocation.getCurrentPosition(success,error); } } });

approot/public/index.html


<!DOCTYPE html>

<html>
	<head>
		<meta charset="utf-8">
		<title> GPS Tracker</title>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
		<script src="js/main.js"></script>
		<link href="css/style.css" rel="stylesheet">

	</head>
	<body>

		<div>
			<h1>Socket.io gps tracker test</h1>
		</div>

		<button id="send">Send Something</button>
		<div id="debug-info"></div>
		<div id="output"></div>
	</body>



</html>
					

style.css


h1{
	font-family:Arial, sans-serif;
	font-size:18px;

}

p,button{
	font-family: Arial,sans-serif;
	font-size:12px;

}
#debug-info{
	position: absolute;left:0;width: 50%;
	top:100px;height:auto;
}
#output{
	position: absolute;left:50%;width: 50%;
	top:100px; height:auto;
}
button{
	border-radius: 0;
	outline: none;
	background:none;
	border-style: solid;
	border-color:black;
}
button:hover{
	background-color: #99ffff;
}
						
					

5 | global access to local server

localhost.run and port forwarding (optional)

Extra | Small Homeworks

1 | Think of another application for a websocket

2 | Scale up your GPS Tracker through a real time MAP visualization