初识WebSocket协议

1.什么是WebSocket协议

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链接。前端

2.应用WebSocket

设想这样一个场景,一个基于B/S架构的应用,其功能是服务器主动向浏览器定时发送一个消息,应该怎么作?因为HTTP协议只能由客户端发起请求,服务器端响应请求创建链接,因此经过HTTP协议实现服务器主动推送消息有必定的难度,能够经过浏览器客户端定时向服务器发送HTTP请求来实现,Comet就是基于这种方式,实际上这并非真正的“服务器主动”。然而依靠WebSocket,咱们可以轻易的作到这一点。java

如今WebSocket的支持状况以下:web

1.服务器端后端

  1. IIS 7.0+
  2. Tomcat 7.0.5+
  3. Jetty t.0+
  4. WebLogic 12c
  5. WebSphere 8.0+

2.浏览器端api

  1. Chrome 4+
  2. FireFox 5+
  3. IE 10+
  4. Safari IOS 5+
  5. Android Browser Android 4.5+

下面咱们将利用WebSocket实现一个简单的java webapp,其功能是服务器主动向浏览器发送三条消息。服务器为Tomcat 8.5.4,除此以外,要为咱们的app引入支持WebSocket的jar包---websocket-api.jar。如需观察其效果,请移步浏览器

代码以下:服务器

前端: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>
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 }
View Code

在Tomcat中使用WebSocket,首先须要在服务器端创建一个endpoint,语法为

@ServerEndpoint("/websocket")

而后在前端根据这个endpoint的url获取一个WebSocket对象,而后调用其相关方法便可。因为代码较为简单,在本文中不在赘述,我会在后续文章中详细分析。

3.WebSocket和TCP、HTTP的关系

WebSocket是一个独立的、基于TCP协议的应用层协议,它和HTTP协议惟一的关系就是WebSocket协议的握手创建链接的过程是由HTTP服务器实现的,而且HTTP服务器将之视为HTTP协议的一个升级版。

PS:个人大部分文章首发在知乎专栏:关于计算机的一些事,欢迎你们关注

相关文章
相关标签/搜索