308364 - WebSocket using Socket.IO

17
ICT@PSU 308-364 Advanced Web Programming 1 of 17 Web Socket using Socket.IO 308-364 Advanced Web Programming 1/2558 Simplicity is the ultimate sophistication Leonardo da Vinci

Transcript of 308364 - WebSocket using Socket.IO

Page 1: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 1 of 17

Web Socket using Socket.IO308-364 Advanced Web Programming

1/2558

Simplicity is the ultimate sophistication

Leonardo da Vinci

Page 2: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 2 of 17

Objectives

• Concepts of the real time communication on Website

• Understand how WebSocket works

• Implement a real time chat using Socket.IO• NodeJS

• Express• Jade

Page 3: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 3 of 17

http://venturebeat.com/2012/08/13/webrtc-is-almost-here-and-it-will-change-the-web/

Real time communication on Website

HTTP (Pre AJAX)

Original Web, one page request returnsOne page (e.g. Geocities).

AJAX (2004)

Page can update without refreshing(e.g. Gmail).

Web Sockets (2008)

Page can establish bi-directionalcommunication (e.g. Trello).

WebRTC (2012)Page to page communications

Page 4: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 4 of 17

WebSocket• Protocol providing full-duplex communication channel

over single TCP connection

• Web was built around the idea – 'Client requests, Server fulfills'

• AJAX got people started to look for bidirectional connections

• Other strategies like long-polling had the problem of carry overhead, leading to increase in latency

Page 5: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 5 of 17

How does WebSocket work?

• Establish connection through 'WebSocket Handshake‘

• After handshake, initial HTTP connection is replaced by WebSocketconnection (uses same underlying TCP/IP)

Transfer data without incurring any overhead associated with requests

GET /chat HTTP/1.1

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Origin: http://example.com

Client Request

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Server Resonse

Page 6: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 6 of 17

What is Socket.IO• A persistent connection between

server & client• Real time and Cross browsers• Socket.IO is composed of two parts:• A server that integrates with (or

mounts on) the Node.JS HTTP Server: socket.io

• A client library that loads on the browser side: socket.io-client

• In addition to one-to-one communication as in WebSocket, it enables broadcasting to multiple nodes

Node Server

socket.io

Browser

socket.io

Browser

socket.io

Browser

socket.io

Page 7: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 7 of 17

Push for changes

Browser Server Notification Server

Load page

connect(WebSocket, Flash Socket, …)

Data changed

Changed data

Update UI

Page 8: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 8 of 17

Installation and Configuration

npm install socket.io

var http = require('http');

var fs = require('fs');

fs.readFile('./index.html', function(err, html) {

var s = http.createServer(function(q, r){

r.writeHead(200, {'Content-Type' : 'text/html'});

r.write(html);

r.end('Hello World');

});

s.listen(80);

});

app.js

Create a web server, and load index.html

Page 9: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 9 of 17

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

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

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

socket.emit(data);

console.log(data);

});

});

app.js (Insert after s.listen(80))

<script src=‘https://cdn.socket.io/socket.io-1.3.3.js’></script>

<script>

var socket = io.connect(http://localhost);

socket.on(‘connect’, function () {

socket.emit(‘EventName’, ‘Hello my socket!’);

});

</script>

index.html

1. Once the index.html is

loaded, the socket.on is

executed.

2. Data are stored in the server

using socket.emit, and shown on console

Page 10: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 10 of 17

Full example

var http = require('http');

var fs = require('fs');

fs.readFile('./index.html', function(err, html) {

var s = http.createServer(function(request, response) {

response.writeHead(200, {"Content-Type":"text/html"});

response.write(html);

response.end('Hello World!');

});

s.listen(80);

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

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

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

socket.emit(data);

console.log(data);

});

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

console.log('client disconnected');

});

});

});

app.js index.html<script src=‘https://cdn.socket.io/socket.io-1.3.3.js’></script>

<script>

var socket = io.connect(http://localhost);

socket.on(‘connect’, function () {

socket.emit(‘EventName’, ‘Hello my socket!’);

});

</script>

Page 11: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 11 of 17

Fire: 1) Individual Recipient

• Using “Emit” to communicate with individual connection

• Current socket

• Specific socket

socket.emit('eventName', "Event Data");

io.sockets.socket(socketId).emit('eventName', "Event Data");

Page 12: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 12 of 17

Fire: 2) Multiple Recipients

• Using “Boardcast” to communicate with multiple connections

• All connected nodes except the current one

• All connected nodes

socket.boardcast.emit('eventName', "Event Data");

io.sockets.emit('eventName', "Event Data");

Page 13: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 13 of 17

Fire: 3) Specific Channel

• Using “To/In” to communicate with specific channel

• To all connected nodes in a channel except current

• To all connected nodes in a channel

socket.boardcast.to(channelName).emit('eventName', "Event Data");

io.sockets.in(channelName).emit('eventName', "Event Data");

Page 14: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 14 of 17

Lab (10%)

• You will follow the guideline in this website to create a chat application.• http://socket.io/get-started/chat/

• http://www.siamhtml.com/real-time-chat-with-node-js-and-socket-io

• You can decorate your own application with your desired framework.

Page 15: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 15 of 17

Install Dependencies

• npm install express --save-dev

• npm install --save socket.io

• npm install jade

• Jade is Optional• If you want to try, you can use jade to create HTML and

JavaScript, but this task is optional.

• https://www.youtube.com/watch?v=pNKNYLv2BpQ

Page 16: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 16 of 17

Express and Jade

• http://expressjs.com/• Fast, un-opinionated, minimalist web framework for Node.js• Express is a minimal and flexible Node.js web application

framework that provides a robust set of features for web and mobile applications.

• Learn Express : http://www.siamhtml.com/how-to-build-website-with-expressjs/

• http://jade-lang.com/• A clean, whitespace-sensitive template language for writing

HTML• Learn Jade : http://www.siamhtml.com/how-to-use-jade-template-

engine-with-express/

Page 17: 308364 - WebSocket using Socket.IO

ICT@PSU 308-364 Advanced Web Programming 17 of 17

If you don’t want to use Jade

doctype html

html

head

title Realtime Chat using Node.js and Socket.IO

meta(name='viewport', content="initial-scale=1")

link(rel='stylesheet', href='css/main.css')

body

div.box.box--container

div.box.box--chat

ul#chat-history

form#chat-form(action="")

input.box(type="text", id="chat-message", autocomplete="off", placeholder="Enter message here...")

<!DOCTYPE html>

<html>

<head>

<title>Realtime Chat using Node.js and Socket.IO</title>

<meta name="viewport" content="initial-scale=1"><link rel="stylesheet" href="css/main.css">

</head>

<body>

<div class="box box--container">

<div class="box box--chat">

<ul id="chat-history"></ul>

<form id="chat-form" action="">

<input type="text" id="chat-message"

autocomplete="off" placeholder="Enter message here..." class="box">

</form>

</div>

</div>

</body>

</html>

Just convert Jade (in the tutorial) to HTML => http://jade-lang.com/demo/