初識WebSocket協議,初識websocket
1.什麼是WebSocket協議
RFC6455文檔的表述如下:
The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists of an opening handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections.
大意是說WebSocket是一個基於TCP協議的全雙工系統的應用程式層協議,主要用於Web瀏覽器,其目的是使基於瀏覽器、需要全雙工系統通訊的web應用不再依賴於多個HTTP串連。
2.應用WebSocket
設想這樣一個情境,一個基於B/S架構的應用,其功能是伺服器主動向瀏覽器定時發送一個訊息,應該怎麼做?由於HTTP協議只能由用戶端發起請求,伺服器端響應請求建立串連,所以通過HTTP協議實現伺服器主動推送訊息有一定的難度,可以通過瀏覽器用戶端定時向伺服器發送HTTP請求來實現,Comet就是基於這種方式,實際上這並不是真正的“伺服器主動”。然而依靠WebSocket,我們能夠輕易的做到這一點。
現在WebSocket的支援情況如下:
1.伺服器端
2.瀏覽器端
下面我們將利用WebSocket實現一個簡單的java webapp,其功能是伺服器主動向瀏覽器發送三條訊息。伺服器為Tomcat 8.5.4,除此之外,要為我們的app引入支援WebSocket的jar包---websocket-api.jar。如需觀察其效果,請移步http://139.129.95.147/TestWebSocket/。
代碼如下:
前端:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Testing websockets</title> 5 </head> 6 <body> 7 <div> 8 <input type="submit" value="Start" onclick="start()" /> 9 </div>10 <div id="messages"></div>11 <script type="text/javascript">12 var webSocket =13 new WebSocket('ws://139.129.95.147/TestWebSocket/websocket');14 webSocket.onerror = function(event) {15 onError(event)16 };17 webSocket.onopen = function(event) {18 onOpen(event)19 };20 webSocket.onmessage = function(event) {21 onMessage(event)22 };23 function onMessage(event) {24 document.getElementById('messages').innerHTML25 += '<br />' + event.data;26 }27 function onOpen(event) {28 document.getElementById('messages').innerHTML29 = 'Connection established';30 }31 function onError(event) {32 alert(event.data);33 }34 function start() {35 webSocket.send('hello');36 return false;37 }38 </script>39 </body>40 </html>index.html
後端:
1 import java.io.IOException; 2 import javax.websocket.OnClose; 3 import javax.websocket.OnMessage; 4 import javax.websocket.OnOpen; 5 import javax.websocket.Session; 6 import javax.websocket.server.ServerEndpoint; 7 @ServerEndpoint("/websocket") 8 public class TestWebSocket { 9 @OnMessage10 public void onMessage(String message, Session session)11 throws IOException, InterruptedException {12 13 // Print the client message for testing purposes14 System.out.println("Received: " + message);15 16 // Send the first message to the client17 session.getBasicRemote().sendText("This is the first server message");18 19 // Send 3 messages to the client every 5 seconds20 int sentMessages = 0;21 while(sentMessages < 3){22 Thread.sleep(5000);23 session.getBasicRemote().24 sendText("This is an intermediate server message. Count: "25 + sentMessages);26 sentMessages++;27 }28 29 // Send a final message to the client30 session.getBasicRemote().sendText("This is the last server message");31 }32 33 @OnOpen34 public void onOpen() {35 System.out.println("Client connected");36 }37 @OnClose38 public void onClose() {39 System.out.println("Connection closed");40 }41 }View Code
在Tomcat中使用WebSocket,首先需要在伺服器端建立一個endpoint,文法為
@ServerEndpoint("/websocket")
然後在前端根據這個endpoint的url擷取一個WebSocket對象,然後調用其相關方法即可。由於代碼較為簡單,在本文中不在贅述,我會在後續文章中詳細分析。
3.WebSocket和TCP、HTTP的關係
WebSocket是一個獨立的、基於TCP協議的應用程式層協議,它和HTTP協議唯一的關係就是WebSocket協議的握手建立串連的過程是由HTTP伺服器實現的,並且HTTP伺服器將之視為HTTP協議的一個升級版。