RFC6455文檔的表述以下:javascript
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.html
大意是說WebSocket是一個基於TCP協議的全雙工的應用層協議,主要用於Web瀏覽器,其目的是使基於瀏覽器、須要全雙工通訊的web應用再也不依賴於多個HTTP鏈接。前端
設想這樣一個場景,一個基於B/S架構的應用,其功能是服務器主動向瀏覽器定時發送一個消息,應該怎麼作?因爲HTTP協議只能由客戶端發起請求,服務器端響應請求創建鏈接,因此經過HTTP協議實現服務器主動推送消息有必定的難度,能夠經過瀏覽器客戶端定時向服務器發送HTTP請求來實現,Comet就是基於這種方式,實際上這並非真正的「服務器主動」。然而依靠WebSocket,咱們可以輕易的作到這一點。java
如今WebSocket的支持狀況以下:web
1.服務器端後端
2.瀏覽器端api
下面咱們將利用WebSocket實現一個簡單的java webapp,其功能是服務器主動向瀏覽器發送三條消息。服務器爲Tomcat 8.5.4,除此以外,要爲咱們的app引入支持WebSocket的jar包---websocket-api.jar。如需觀察其效果,請移步http://139.129.95.147/TestWebSocket/。瀏覽器
代碼以下:服務器
前端:websocket
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').innerHTML 25 += '<br />' + event.data; 26 } 27 function onOpen(event) { 28 document.getElementById('messages').innerHTML 29 = '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>
後端:
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 @OnMessage 10 public void onMessage(String message, Session session) 11 throws IOException, InterruptedException { 12 13 // Print the client message for testing purposes 14 System.out.println("Received: " + message); 15 16 // Send the first message to the client 17 session.getBasicRemote().sendText("This is the first server message"); 18 19 // Send 3 messages to the client every 5 seconds 20 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 client 30 session.getBasicRemote().sendText("This is the last server message"); 31 } 32 33 @OnOpen 34 public void onOpen() { 35 System.out.println("Client connected"); 36 } 37 @OnClose 38 public void onClose() { 39 System.out.println("Connection closed"); 40 } 41 }
在Tomcat中使用WebSocket,首先須要在服務器端創建一個endpoint,語法爲
@ServerEndpoint("/websocket")
而後在前端根據這個endpoint的url獲取一個WebSocket對象,而後調用其相關方法便可。因爲代碼較爲簡單,在本文中不在贅述,我會在後續文章中詳細分析。
WebSocket是一個獨立的、基於TCP協議的應用層協議,它和HTTP協議惟一的關係就是WebSocket協議的握手創建鏈接的過程是由HTTP服務器實現的,而且HTTP服務器將之視爲HTTP協議的一個升級版。
PS:個人大部分文章首發在知乎專欄:關於計算機的一些事,歡迎你們關注