Está en la página 1de 58

Lic.

Jorge Guerra Guerra

WebSocket
Comunicación entre procesos

 •Es la cooperación entre procesos para lograr


un objetivo global. (Cada proceso hace su
labor).
 •Dos Formas
 –Procesos locales
 –Procesos Remotos

Lic. Jorge Guerra Guerra 2


Comunicación en Sistemas Distribuidos

 Red de comunicación es elemento


fundamental para comunicación entre
procesos.
 Dos modelos de comunicación entre
procesos:
 Memoria compartida.
 zona común en que los mensajes podrán ser
compartidos entre cliente y servidor , la base de
datos distribuida es un ejemplo de uso.
Lic. Jorge Guerra Guerra 3
Memoria compartida

Declaración independiente de variables


P ro c e s o A P ro c e s o B

T e x to T e x to
D a to s
v a r2
D a to s
v a r1

P ila S e g m e n to P ila
d e m e m o r ia
c o m p a r tid a

Lic. Jorge Guerra Guerra 4


Modelos de comunicación (cont)
 Paso de mensajes
 En este modelo el proceso cliente y el proceso
servidor se encuentran en máquinas distintas y
no tienen ningún elemento común entre ellos,
por lo que solo se servirán del medio de
comunicación para intercambiarse mensajes.

Lic. Jorge Guerra Guerra 5


Paso de mensajes

 Permite resolver:
 Exclusión mutua
 Sincronizar un proceso que recibe un mensaje y otro que lo envía
 Comunicación de datos entre espacios de memoria diferentes (mismo
computador, diferentes computadores)

 Primitivas básicas:
 send(destino, mensaje) envía un mensaje al proceso destino
 receive(destino, mensaje) recibe un mensaje del proceso destino

Lic. Jorge Guerra Guerra 6


Modelo de paso de mensajes

Lic. Jorge Guerra Guerra 7


Paso de mensajes

 Múltiples soluciones

 Aspectos de diseño
 Tamaño del mensaje
 Flujo de datos (unidireccional, bidireccional)
 Nombrado  Directo
 Indirecto (puertos, colas)
 Sincronización (síncrono, asíncrono)
 Almacenamiento

Lic. Jorge Guerra Guerra 8


Uso de colas y puertos

P r o c e s o c lie n te P r o c e s o c lie n te
send
P r o c e s o c lie n te P r o c e s o c lie n te
r e c e iv e
send
P u e rto

m e n s a je
m e n s a je

C o la d e m e n s a je s

C o m u n ic a c ió n c o n C o m u n ic a c ió n c o n p u e r t o s
c o la s d e m e n s a je s

Lic. Jorge Guerra Guerra 9


Tipos de paso de mensajes
 Paso de mensajes puro

Llamada a procedimientos remotos

Invocación a métodos remotos

Lic. Jorge Guerra Guerra 10


Fundamentos de la comunicación entre procesos

 Procesos en diferentes maquinas. Se


requiere:
 Una red de comunicaciones
 Lenguaje común de comunicaciones
 Protocolo de transporte

Lic. Jorge Guerra Guerra 11


Niveles de Comunicación

Lic. Jorge Guerra Guerra 12


Tipos de comunicacion

 Comunicación asíncrona - el remitente


continúa inmediatamente después de enviar
el mensaje, el mensaje se almacena en un
búfer local.
 Comunicación Síncrona - el remitente está
bloqueado hasta que el mensaje sea
almacenado en un búfer del host receptor, o
efectivamente sea entregado al receptor

Lic. Jorge Guerra Guerra 13


Las capas TCP/IP

mail, file transfer, web


Application Application

tcp, udp
Transport Transport
ip
Internet Internet Internet Internet

Media access Media access Media access Media access

Lic. Jorge Guerra Guerra 14


Protocolos en TCP/IP

Lic. Jorge Guerra Guerra 15


TCP y UDP para Cliente / Servidor

request

response

UDP

TCP T/TCP

Lic. Jorge Guerra Guerra 16


Socket
 Se considera como un extremo de una conexión
de comunicación entre dos computadoras. Por
otro lado, si lo vemos del punto de vista de la
programación un socket representa el
mecanismo para transferir datos de una
computadora a otra

Lic. Jorge Guerra Guerra 17


Como funciona el socket

Lic. Jorge Guerra Guerra 18


Socket dentro del modelo TCP/IP

Lic. Jorge Guerra Guerra 19


The concept of “Real Time Web” is
awesome.

Trying to program it really stinks.


Lic. Jorge Guerra Guerra 20
Introduction

The Web becomes more and more

pervasive interactive social mobile

Necessity of evolution to a platform for real-time


data exchange
WebSocket technology is the fundament

Lic. Jorge Guerra Guerra 21


Status of Web Communication

The HTTP Protocol


 Designed for document transmission
 Cumbersome, nearly real-time tricks
▪ Polling, Long-Polling
▪ Reverse-AJAX, Comet etc.
 Ultimately non-standardized hacks
 Remains a Request/Response mechanism

Lic. Jorge Guerra Guerra 22


Existing Polling Methods
To workaround the limitations of HTTP
Server

Pollin
g
Client
Polling interval

Server

Long
Pollin
g Lic. Jorge Guerra Guerra Client 23
1. Frequent polling
HTTP Request

HTTP Response

Browser Server

Lic. Jorge Guerra Guerra 25


GET /PollingStock//PollingStock HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102
Firefox/3.5.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.example.com/PollingStock/
Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false;
showInheritedProperty=false; showInheritedProtectedProperty=false;
showInheritedMethod=false; showInheritedProtectedMethod=false; s
howInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false

HTTP/1.x 200 OK
X-Powered-By: Servlet/2.5
Server: Sun Java System Application Server 9.1_02
Content-Type: text/html;charset=UTF-8
Lic. Jorge Guerra Guerra 26
Request / Response headers = 871 bytes
1000 clients poll every 10 seconds

1000 * 871 bytes = 0,8MB / 10 seconds


0,8 MB * 6 = 4,8 MB / minute
4,8 MB * 60 = 288 MB / hour

288 MB * 24 = 6,912 GB / day

Lic. Jorge Guerra Guerra 27


2. Long polling
Wait for it...
HTTP Request

Browser Server

HTTP Response

Lic. Jorge Guerra Guerra 29


HTML5


WHATWG, excinsión de W3C

Tags HTML + objetos JavaScript + CSS3
 Multimedia
 Interactividad
 Estilos y efectos visuales

Muerte de Flash
 Adobe Edge

Aplicaciones Web

Lic. Jorge Guerra Guerra 30


Comunicaciones en HTML5


WebSockets

Server-Sent Events

Cross-document messaging

Channel messaging

WebRTC DataChannels
¡¡¡Todos con el mismo API!!!

Lic. Jorge Guerra Guerra 31


WebSockets

a socket that works anywhere across the web


…even through network intermediaries
 Bidirectional Server
 Single TCP socket
 In & out of browser Open WebSocket Connection
 Real time performance
 Simple programming
Client
model
 Bandwidth savings
 Scalability advantages
Lic. Jorge Guerra Guerra 32
‘TCP for the Web’
Full-duplex direct
communication
HTTP

HTTP

WebSocket

Browser Server
WebSocket

Lic. Jorge Guerra Guerra 34


Lic. Jorge Guerra Guerra 35
WebSockets Specification – Two Key
Pieces

WEBSOCKETS PROTOCOL W3C WEBSOCKETS API


HYBI WORKING GROUP WEB APPLICATIONS WORKING GROUP

Lic. Jorge Guerra Guerra 36


WebSockets – Technology

What are WebSockets?


 Bidirectional, full-duplex, permanent TCP connections
400 times less overhead
⅓ of latency
 Standardized in HTML5 by W3C & IETF
protects investments
 Single TCP port
saves 50% server resources

Lic. Jorge Guerra Guerra 37


WebSockets – Technology

What else?
 Designed for interactive
Web Applications
 Open for all kind of
stationary and mobile
browser based and native apps
 Not just a protocol, but a new paradigm
Request/Response Real-Time
Communication

Lic. Jorge Guerra Guerra 38


WebSockets – Targets

Demand from Developers, Providers and


Users
 Compatibility
Interoperability
 Independency
Integratability
 Reliability
Security

Lic. Jorge Guerra Guerra 39


WebSockets – Targets

Demand from Developers, Providers and


Users
 Availability
Scalability
 Extendability
Flexibility
 Simplicity
Maintainability

Lic. Jorge Guerra Guerra 40


A Closer Look:
Programming WebSockets
Opening Handshake
HTTP Upgrade Request
HTTP TCP HTTP
1 Client Server

GET /chat HTTP/1.1


Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key:
dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Origin:
http://example.com
Sec-WebSocket-Version: 6

Lic. Jorge Guerra Guerra 42


Opening Handshake
HTTP Upgrade Request
HTTP TCP HTTP
1 Client Server

HTTP TCP HTTP


2 Client Server
HTTP Switching Protocols Response

HTTP/1.1 101 Switching Protocols


Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept:
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Lic. Jorge Guerra Guerra 43


Opening Handshake
HTTP Upgrade Request
HTTP TCP HTTP
1 Client Server

HTTP TCP HTTP


2 Client Server
HTTP Switching Protocols Response

Web TCP WebSocket Messages Web


3 Socket Socket
WebSocket Messages

Binary or UTF8
Messages or streams

Lic. Jorge Guerra Guerra 44


Lic. Jorge Guerra Guerra 45
HTML5
"A new kid on the block"
Introducing new features for drawing, networking and
background processing (among other things) .
• Canvas tags for drawing
• Web sockets for networking
• Web workers for background processing
• Web storage for persistent data storage
 
HTML5 supported by W3C since October 2006.
W3C abandoned own work with XHTML 2.0 in favor of
HTML5 late 2009.
HTML5 is here to stay.
Web Sockets

More than an alternative to the XMLHttpRequest object


used for AJAX:
• Bi-directional, full-duplex communications channel.
• Designed to be implemented in web browsers and
web servers.
• Extremely low overhead for payloads, only two
bytes!
 
API standardized by the W3C and the protocol is being
standardized by the IETF.
WebSocket API

Lic. Jorge Guerra Guerra 48


Web Sockets Protocol Handshake

Client to the server: Server response:

GET / HTTP/1.1 HTTP/1.1 101 Web Socket Protocol Handshake


Upgrade: WebSocket Upgrade: WebSocket 
Connection: Upgrade Connection: Upgrade 
Host: localhost:9877 WebSocket-Origin: http://localhost:8080 
Origin: http://localhost:8080 WebSocket-Location: ws://localhost:9877/ 
\r\n\r\n WebSocket-Protocol: sample
\r\n\r\n
Web Sockets Payload Protocol

Each frame starts with a 0x00 byte, ends with a 0xFF


byte, and contains UTF-8 data in between.
 
The API is standardized by the W3C and the protocol is
being standardized by the IETF.
Web Sockets example

Client side: Server response (payload data):


var ws = new os.write (0x00);
WebSocket("ws://localhost:9877/"); String payload = "Some data";
ws.onopen = function (e) { os.write (payload.getBytes ("utf-8"));
alert("Connected to Control Server");  os.write (0xff);
}; os.flush ();
ws.onclose = function (e) {
alert("Connection closed");
};
ws.onmessage = function (e) {
alert("Received data = "+e.data);
};
 
Browser Support
IE9: No
Safari 5, Chrome 10:Yes
FireFox 4, Opera 11: Yes, but…

Mobile: No, only Safari :-(

Source: http://caniuse.com

Lic. Jorge Guerra Guerra 52


ALTERNATIVES

yesssss
Silverlight
Flash

Lic. Jorge Guerra Guerra 53


Servidores disponibles

Lic. Jorge Guerra Guerra 54


Cont.

Lic. Jorge Guerra Guerra 55


Cont.

Lic. Jorge Guerra Guerra 56


Modelos de comunicación Web

Lic. Jorge Guerra Guerra 57


Comunicación Web (HTML 5)

Lic. Jorge Guerra Guerra 58

También podría gustarte