Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Websocket

1,859 views

Published on

艾鍗教你從實作中認識物聯網!

http://bit.ly/2jZRwt2

課程使用Raspberry Pi結合ARM mbed Cloud來實現一個物聯網解決方案。你會了解M2M(Machine-to-Machine)網路協定,包含CoAP、MQTT、LWM2M等協定,並藉由Raspberry Pi連接 Cloud。 Raspberry Pi的部份教你連接一些感測器,包含GPIO、數位界面I2C的溫溼度感測器、類比感測器如光感應器等,並將這些感測器成為定義為不同的Resource Path並註冊在mbed cloud中。
本課程將採用Node.js撰寫WebAPP,使用HTTP/RESTful API存取Resource。在實作WebAPP中,除了後端Node.js,你也將會看到後端如何與前端瀏覽器之間要如何溝通的方式,如AJAX或WebSocket

Published in: Engineering
  • Login to see the comments

Websocket

  1. 1. The WebSocket Protocol joseph@艾鍗學院 2016/09/11
  2. 2. HTTP Issue Depends on Request / Response architecture • Only client can send Requests • Server can only Respond to Requests • Can’t send another Request before Response Too much traffic overhead & header on every Request / Response HTTP is Good For Docs Not Apps
  3. 3. HTTP Header (too much traffic overhead!!) HTTP Client Server
  4. 4. HTTP 改善方法 避免一來一回: 使用AJAX 達到非同步通訊 (但依然需要發出請求, 因為這還是polling) 避免過多的polling traffic ,使用Long Polling (這也會消耗伺服器頻寬和資源,且還是half-duplex) 固定http Header size且改成binary協定, 且要做成 Full-duplex
  5. 5. 各種Web 通訊方法
  6. 6. Long Polling技術 An attempt to offer realtime server interaction, using a persistent or long-lasting HTTP connection between the server and the client. The browser makes an Ajax-style request to the server, which is kept open until the server has new data to send to the browser, which is sent to the browser in a complete response. The browser initiates a new long polling request in order to obtain subsequent events. Specific technologies:
  7. 7. WebSockets - Sockets on the Web ● Part of HTML5 ● W3C API and IETF Protocol (RFC 6455 ) ● Full-duplex, bidirectional communication ● Unsecured (TCP) and secured (SSL) modes ● Traverses firewalls, proxies and routers ● Text (UTF-8) and binary data ● Ping/Pong messages for keep-alive ● Share ports 80 and 443 with HTTP/HTTPS
  8. 8. WebSocket A WebSocket is a standard bidirectional TCP 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 with full duplex mode WebSocket Client WebSocket Server
  9. 9. WebSocket優點 • 傳送的HTTP Request Header僅2bytes • 伺服器可主動Push資料給用戶端,而不是總是傳統HTTP Request/Response的Cycle(half-duplex),
  10. 10. WebSocket Connection Process The client requesting a webSocket connection, sends an HTTP request to the server on port 80. That HTTP request is a perfectly legal HTTP request, but it has a header included on it Upgrade: websocket. If the server supports the webSocket protocol, then it responds with a legal HTTP response with a 101 status code that includes a header Connection: Upgrade. At that point, both sides then switch protocols to the webSocket protocol and all future communication on that socket is done using the data format for the webSocket frame. Any other incoming HTTP requests that do not contain the upgrade request header are treated as normal HTTP requests
  11. 11. ScreenShot From WireShark
  12. 12. 透過HTTP請求升級 成WebSocket通訊 HTTP "101 Switching Protocols" 同意接受升級
  13. 13. Packet Opcodes (Types) 0 - continuation frame 1 - text frame (UTF-8) 2 - binary frame 3-7 - reserved (data) 8 - connection close 9 - ping 10 - pong 11-15 - reserved (control)
  14. 14. WebSocket frame 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 F I N R S V 1 R S V 2 R S V 3 opcode(4) M A S K payload len(7) extended payload len(16/64) extended payload len continued(16/64) masking key(0/32) masking key continued payload ...
  15. 15. The WebSockets API
  16. 16. socket.io socket.io : Cross browser way to do JavaScript-based real time communication is socket.io uses WebSockets if the client supports it, and falls back on other things if it’s not, and even has AJAX polling and multi-part streaming
  17. 17. Sending and receiving events Socket.IO allows you to emit and receive custom events. Besides connect, message and disconnect, you can emit custom events Socket.IO allows you to emit and receive custom events. Besides connect, message and disconnect, you can emit custom events:
  18. 18. Node.js Socket.IO (Web Socket Server) npm install socket.io var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); io代表所有sockets socket 代表單一連入的socket
  19. 19. Node.js Socket.IO (Web Socket Client) <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body>
  20. 20. 實驗: Websocket
  21. 21. 探討: 使用AJAX由於Client不斷發出HTTP Request給Server確認是 否有資料回傳,而HTTP Request Header占了大量的Bytes, 傳送時不僅占了大量網路頻寬,對Server資源的消耗量也 會變大。
  22. 22. 實驗: Polling SetInterval() 與SetTimeout() 差異 輪詢(polling)是讓瀏覽器每隔一段時間就自動送出一個 HTTP 請求給伺服器
  23. 23. 使用setInterval() 可能會有這個問題! a=1 a=2a=0 a=1 a=2 a=1 Time
  24. 24. 使用setTimeout() 可以避免錯亂! Using setTimeout() doesn’t guarantee execution on a fixed interval per se. But, it does guarantee that the previous interval has completed before the next interval is called a=1 a=2a=0 a=1 a=2 Time
  25. 25. Read More • Socket.IO : http://socket.io • RFC 6455 - The WebSocket Protocol - IETF Tools

×