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.服务器端
- IIS 7.0+
- Tomcat 7.0.5+
- Jetty t.0+
- WebLogic 12c
- WebSphere 8.0+
2.浏览器端
- Chrome 4+
- FireFox 5+
- IE 10+
- Safari IOS 5+
- Android Browser Android 4.5+
下面我们将利用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‘).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>
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 @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对象,然后调用其相关方法即可。由于代码较为简单,在本文中不在赘述,我会在后续文章中详细分析。
3.WebSocket和TCP、HTTP的关系
WebSocket是一个独立的、基于TCP协议的应用层协议,它和HTTP协议唯一的关系就是WebSocket协议的握手建立连接的过程是由HTTP服务器实现的,并且HTTP服务器将之视为HTTP协议的一个升级版。