70 likes | 223 Views
Real Time Web. Part 2. Web Sockets. New HTML 5 protocol full-duplex bi-directional TCP connection client – server interaction. Web Socket Protocol. Designed to work with existing Web infrastructure ws : or wss : ws ://html5Rocks.websocket.org/echo Client makes GET request
E N D
Real Time Web Part 2
Web Sockets • New HTML 5 protocol • full-duplex • bi-directional • TCP connection • client – server interaction
Web Socket Protocol • Designed to work with existing Web infrastructure ws: or wss: • ws://html5Rocks.websocket.org/echo • Client makes GET request • Server responds with Upgrade header • Client – Server connected over underlying TCP/IP connection
Client Side • JavaScript • URL to server • Optional subprotocols • Event handlers similar to Server-Sent Events varconnection = newWebSocket(‘ws://html5rocks.websocket.org/echo’, [‘soap’, ‘xmpp’]); connection.onopen = function () { connection.send(‘Ping’); // Send the message Ping to the server } connection.onerror = function (error) { console.log(‘WebSocket Error ‘ + error); } connection.onmessage = function (e) { console.log(‘Server: ‘ + e.data); }
Communicating with Server • Send data to Server with ‘send’ function // Sending a String connection.send(‘an interesting message’); // Sending canvas ImageData as ArrayBuffer varimg = canvas_content.getImageData(0, 0, 400, 300); varbinary = new Uint8Array(img.data.length); for (vari = 0; i < img.data.length; i++) { binary[i] = img.data[i]; } connection.send(binary.buffer); // Sending file as Blob varfile = document.querySelector(‘input[type=“file”]’).files[0]; connection.send(file);
Web Socket Information • Supported Protocols • Supported Extensions varconnection = newWebSocket(‘ws://html5rocks.websocket.org/echo’, [‘soap’, ‘xmpp’]); // print protocols to console console.log(connection.protocol); varconnection = newWebSocket(‘ws://html5rocks.websocket.org/echo’, [‘soap’, ‘xmpp’]); // print extensions to console console.log(connection.extensions);
Remember • Web Sockets are like regular Sockets • Both sides must agree on what is sent • They must handle the data on the socket • They are very powerful