认识HTML5的WebSocket以及spring+websocket整合

来源:互联网 发布:青岛安全网络教育平台 编辑:程序博客网 时间:2024/05/16 20:58

今天需要做一个websocket的后台服务demo,以前没接触过,所以今天转载了下别人的东东,学习下。
认识HTML5的WebSocket
在HTML5规范中,我最喜欢的Web技术就是正迅速变得流行的WebSocket API。WebSocket提供了一个受欢迎的技术,以替代我们过去几年一直在用的Ajax技术。这个新的API提供了一个方法,从客户端使用简单的语法有效地推动消息到服务器。让我们看一看HTML5的WebSocket API:它可用于客户端、服务器端。而且有一个优秀的第三方API,名为Socket.IO。

一、什么是WebSocket API?

WebSocket API是下一代客户端-服务器的异步通信方法。该通信取代了单个的TCP套接字,使用ws或wss协议,可用于任意的客户端和服务器程序。WebSocket目前由W3C进行标准化。WebSocket已经受到Firefox 4、Chrome 4、Opera 10.70以及Safari 5等浏览器的支持。

WebSocket API最伟大之处在于服务器和客户端可以在给定的时间范围内的任意时刻,相互推送信息。WebSocket并不限于以Ajax(或XHR)方式通信,因为Ajax技术需要客户端发起请求,而WebSocket服务器和客户端可以彼此相互推送信息;XHR受到域的限制,而WebSocket允许跨域通信。

Ajax技术很聪明的一点是没有设计要使用的方式。WebSocket为指定目标创建,用于双向推送消息。

二、WebSocket API的用法

只专注于客户端的API,因为每个服务器端语言有自己的API。下面的代码片段是打开一个连接,为连接创建事件监听器,断开连接,消息时间,发送消息返回到服务器,关闭连接。

[Copy to clipboard] [ - ]
CODE:
// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:8080'); 

// 打开Socket 
socket.onopen = function(event) { 

  // 发送一个初始化消息
  socket.send('I am the client and I\'m listening!'); 

  // 监听消息
  socket.onmessage = function(event) { 
    console.log('Client received a message',event); 
  }; 

  // 监听Socket的关闭
  socket.onclose = function(event) { 
    console.log('Client notified socket has closed',event); 
  }; 

  // 关闭Socket.... 
  //socket.close() 
};

让我们来看看上面的初始化片段。参数为URL,ws表示WebSocket协议。onopen、onclose和onmessage方法把事件连接到Socket实例上。每个方法都提供了一个事件,以表示Socket的状态。

onmessage事件提供了一个data属性,它可以包含消息的Body部分。消息的Body部分必须是一个字符串,可以进行序列化/反序列化操作,以便传递更多的数据。

WebSocket的语法非常简单,使用WebSockets是难以置信的容易……除非客户端不支持WebSocket。IE浏览器目前不支持WebSocket通信。如果你的客户端不支持WebSocket通信,下面有几个后备方案供你使用:

Flash技术 —— Flash可以提供一个简单的替换。 使用Flash最明显的缺点是并非所有客户端都安装了Flash,而且某些客户端,如iPhone/iPad,不支持Flash。

AJAX Long-Polling技术 —— 用AJAX的long-polling来模拟WebSocket在业界已经有一段时间了。它是一个可行的技术,但它不能优化发送的信息。也就是说,它是一个解决方案,但不是最佳的技术方案。

由于目前的IE等浏览器不支持WebSocket,要提供WebSocket的事件处理、返回传输、在服务器端使用一个统一的API,那么该怎么办呢?幸运的是,Guillermo Rauch创建了一个Socket.IO技术。

三、带Socket.IO的WebSocket

Socket.IO是Guillermo Rauch创建的WebSocket API,Guillermo Rauch是LearnBoost公司的首席技术官以及LearnBoost实验室的首席科学家。Socket.IO使用检测功能来判断是否建立WebSocket连接,或者是AJAX long-polling连接,或Flash等。可快速创建实时的应用程序。Socket.IO还提供了一个NodeJS API,它看起来非常像客户端API。
建立客户端Socket.IO

Socket.IO可以从GitHub下载,可以把socket.io.js文件包含到页面中:

[Copy to clipboard] [ - ]
CODE:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
[/code

此时,Socket.IO在此页面上是有效的,是时候创建Socket了:

[code]
// 创建Socket.IO实例,建立连接
var socket= new io.Socket('localhost',{ 
  port: 8080 
}); 
socket.connect(); 

// 添加一个连接监听器
socket.on('connect',function() { 
  console.log('Client has connected to the server!'); 
});

// 添加一个连接监听器
socket.on('message',function(data) { 
  console.log('Received a message from the server!',data); 
});

// 添加一个关闭连接的监听器
socket.on('disconnect',function() { 
  console.log('The client has disconnected!'); 
}); 

// 通过Socket发送一条消息到服务器
function sendMessageToServer(message) { 
  socket.send(message); 
}

Socket.IO简化了WebSocket API,统一了返回运输的API。传输包括:
WebSocket
Flash Socket
AJAX long-polling
AJAX multipart streaming
IFrame
JSONP polling

你还可以设置任意的Socket.IO构造器的第二个选项,选项包括:

port - 待连接的端口
transports - 一个数组,包含不同的传输类型
transportOptions - 传输的参数使用的对象,带附加属性

Socket.IO还提供了由本地WebSocket API提供的普通连接、断开连接、消息事件。Socket还提供了封装每个事件类型的方法。

四、NodeJS和Socket.IO联合开发

Socket.IO提供的服务器端解决方案,允许统一的客户端和服务器端的API。使用Node,你可以创建一个典型的HTTP服务器,然后把服务器的实例传递到Socket.IO。从这里,你创建连接、断开连接、建立消息监听器,跟在客户端一样。

一个简单的服务器端脚本看起来如下:

[Copy to clipboard] [ - ]
CODE:
// 需要HTTP 模块来启动服务器和Socket.IO
var http= require('http'), io= require('socket.io'); 

// 在8080端口启动服务器
var server= http.createServer(function(req, res){ 
  // 发送HTML的headers和message
  res.writeHead(200,{ 'Content-Type': 'text/html' }); 
  res.end('<h1>Hello Socket Lover!</h1>'); 
}); 
server.listen(8080); 

// 创建一个Socket.IO实例,把它传递给服务器
var socket= io.listen(server); 

// 添加一个连接监听器
socket.on('connection', function(client){ 

  // 成功!现在开始监听接收到的消息
  client.on('message',function(event){ 
    console.log('Received message from client!',event); 
  }); 
  client.on('disconnect',function(){ 
    clearInterval(interval); 
    console.log('Server has disconnected'); 
  }); 
});

你可以运行服务器部分,假定已安装了NodeJS,从命令行执行:

[Copy to clipboard] [ - ]
CODE:
node socket-server.js

现在客户端和服务器都能来回推送消息了!在NodeJS脚本内,可以使用简单的JavaScript创建一个定期消息发送器:

[Copy to clipboard] [ - ]
CODE:
// 创建一个定期(每5秒)发送消息到客户端的发送器
var interval= setInterval(function() { 
  client.send('This is a message from the server! ' + new Date().getTime()); 
},5000);

服务器端将会每5秒推送消息到客户端!

五、dojox.Socket和Socket.IO

Persevere的创建者Kris Zyp创建了dojox.Socket。dojox.Socket以Dojo库一致的方式封装了WebSocket API,用于在客户端不支持WebSocket时,使用long-polling替代。

下面是怎样在客户端使用dojox.Socket和在服务器端使用Socket.IO的例子:

[Copy to clipboard] [ - ]
CODE:
var args, ws= typeof WebSocket!= 'undefined'; 
var socket= dojox.socket(args= { 
  url: ws? '/socket.io/websocket' : '/socket.io/xhr-polling', 
  headers:{ 
    'Content-Type':'application/x-www-urlencoded' 
  }, 
  transport: function(args, message){ 
    args.content = message; // use URL-encoding to send the message instead of a raw body 
    dojo.xhrPost(args); 
  }; 
}); 
var sessionId; 
socket.on('message', function(){ 
  if (!sessionId){ 
    sessionId= message; 
    args.url += '/' + sessionId; 
  }else if(message.substr(0, 3) == '~h~'){ 
   // a heartbeat 
  } 
});

dojox.socket.Reconnect还创建了在套接字失去连接时自动重连。期待包含dojox.Socket的Dojo 1.6版本早日发布。

六、实际应用和WebSocket资源

有很多WebSocke的实际应用。WebSocket对于大多数客户机-服务器的异步通信是理想的,在浏览器内聊天是最突出的应用。WebSocket由于其高效率,被大多数公司所使用。

WebSocket资源
Socket.IO站点:http://socket.io/
WebSocket的Wikipedia:http://en.wikipedia.org/wiki/WebSockets
WebSockets.org站点:http://www.websockets.org/
Dojo WebSocket站点:http://www.sitepen.com/blog/2010/10/31/dojo-websocket



java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序:

Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7:

http://download.csdn.net/detail/up19910522/7719087


spring4.0以后加入了对websocket技术的支持,撸主目前的项目用的是SSM(springMVC+spring+MyBatis)框

架,所以肯定要首选spring自带的websocket了,好,现在问题来了,撸主在网上各种狂搜猛找,拼凑了几个自称

spring websocket的东东,下来一看,废物,其中包括从github上down下来的。举个例子,在搭建过程中有个问题,

撸主上谷歌搜索,总共搜出来三页结果共30条左右,前15条是纯英文的  后15条是韩语和日语,而这30条结果都不能

解决撸主的问题,无奈,只好上官网看全英帮助,在撸主惊人的毅力和不懈奋斗下,纠结了两天的spring+websocket

整合今天算是彻底搭建成功,摸索透彻了。

websocket是目前唯一真正实现全双工通信的服务器向客户端推的互联网技术,与长连接和轮询技术相比,

websocket的优越性不言自明,长连接的连接资源(线程资源)随着连接数量的增多,必会耗尽,客户端轮询会给服

务器造成很大的压力,而websocket是在物理层非网络层建立一条客户端至服务器的长连接,以此来保证服务器向客

户端的即时推送,既不耗费线程资源,又不会不断向服务器轮询请求。

下面言归正传,讲一讲撸主在SSM(springMVC+spring+MyBatis)框架中集成websocket技术的曲折蛋疼直至成功喜悦之路。

  • 1 在maven的pom.xml中加入websocket所依赖的jar包,什么,你不知道maven,快去度之或者查看撸主关于maven的博文恶补一下,spring-websocket所依赖的jar包有以下几个:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <dependency>  
  2.     <groupId>javax.servlet</groupId>  
  3.     <artifactId>javax.servlet-api</artifactId>  
  4.     <version>3.1.0</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>com.fasterxml.jackson.core</groupId>  
  8.     <artifactId>jackson-core</artifactId>  
  9.     <version>2.3.0</version>  
  10. </dependency>  
  11. <dependency>  
  12.     <groupId>com.fasterxml.jackson.core</groupId>  
  13.     <artifactId>jackson-databind</artifactId>  
  14.     <version>2.3.0</version>  
  15. </dependency>  
  16. <dependency>  
  17.    <groupId>org.springframework</groupId>  
  18.    <artifactId>spring-websocket</artifactId>  
  19.    <version>4.0.1.RELEASE</version>  
  20. </dependency>  
  21. <dependency>  
  22.    <groupId>org.springframework</groupId>  
  23.    <artifactId>spring-messaging</artifactId>  
  24.    <version>4.0.1.RELEASE</version>  
  25. </dependency>  

  • 2 更新web.xml中namespace.xsd的版本,

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:websocket="http://www.springframework.org/schema/websocket"  
  4.        xsi:schemaLocation="  
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  6.         http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">  

  • 3 更新spring框架的jar包至4.0以上(spring-core, spring-context, spring-web and spring-webmvc)

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <dependency>  
  2. <span style="white-space:pre">    </span><groupId>org.springframework</groupId>  
  3.     <artifactId>spring-core</artifactId>  
  4.     <version>${spring.version}</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>org.springframework</groupId>  
  8.     <artifactId>spring-web</artifactId>  
  9.     <version>${spring.version}</version>  
  10. </dependency>  
  11. <dependency>  
  12.     <groupId>org.springframework</groupId>  
  13.     <artifactId>spring-webmvc</artifactId>  
  14.     <version>${spring.version}</version>  
  15. </dependency>  
  16. <dependency>  
  17.     <groupId>org.springframework</groupId>  
  18.     <artifactId>spring-context-support</artifactId>  
  19.     <version>${spring.version}</version>  
  20. </dependency>  

  • 4  4.1创建websocket处理类

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package com.up.websocket.handler;  
  2.   
  3. import org.springframework.web.socket.TextMessage;  
  4. import org.springframework.web.socket.WebSocketSession;  
  5. import org.springframework.web.socket.handler.TextWebSocketHandler;  
  6.   
  7. public class WebsocketEndPoint extends TextWebSocketHandler {  
  8.   
  9.     @Override  
  10.     protected void handleTextMessage(WebSocketSession session,  
  11.             TextMessage message) throws Exception {  
  12.         super.handleTextMessage(session, message);  
  13.         TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
  14.         session.sendMessage(returnMessage);  
  15.     }  
  16. }  

  • 4.2创建握手(handshake)接口

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package com.up.websocket;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import org.springframework.http.server.ServerHttpRequest;  
  6. import org.springframework.http.server.ServerHttpResponse;  
  7. import org.springframework.web.socket.WebSocketHandler;  
  8. import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;  
  9.   
  10. public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{  
  11.   
  12.     @Override  
  13.     public boolean beforeHandshake(ServerHttpRequest request,  
  14.             ServerHttpResponse response, WebSocketHandler wsHandler,  
  15.             Map<String, Object> attributes) throws Exception {  
  16.         System.out.println("Before Handshake");  
  17.         return super.beforeHandshake(request, response, wsHandler, attributes);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void afterHandshake(ServerHttpRequest request,  
  22.             ServerHttpResponse response, WebSocketHandler wsHandler,  
  23.             Exception ex) {  
  24.         System.out.println("After Handshake");  
  25.         super.afterHandshake(request, response, wsHandler, ex);  
  26.     }  
  27.   
  28. }  

  • 5 处理类和握手协议的spring配置(applicationContext.xml文件)

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <bean id="websocket" class="com.up.websocket.handler.WebsocketEndPoint"/>  
  2.   
  3. <websocket:handlers>  
  4.     <websocket:mapping path="/websocket" handler="websocket"/>  
  5.     <websocket:handshake-interceptors>  
  6.     <bean class="com.up.websocket.HandshakeInterceptor"/>  
  7.     </websocket:handshake-interceptors>  
  8. </websocket:handlers>  


  • 6 客户端页面

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title>  
  5.     <style type="text/css">  
  6.         #connect-container {  
  7.             float: left;  
  8.             width: 400px  
  9.         }  
  10.   
  11.         #connect-container div {  
  12.             padding: 5px;  
  13.         }  
  14.   
  15.         #console-container {  
  16.             float: left;  
  17.             margin-left: 15px;  
  18.             width: 400px;  
  19.         }  
  20.   
  21.         #console {  
  22.             border: 1px solid #CCCCCC;  
  23.             border-right-color: #999999;  
  24.             border-bottom-color: #999999;  
  25.             height: 170px;  
  26.             overflow-y: scroll;  
  27.             padding: 5px;  
  28.             width: 100%;  
  29.         }  
  30.   
  31.         #console p {  
  32.             padding: 0;  
  33.             margin: 0;  
  34.         }  
  35.     </style>  
  36.   
  37.     <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>  
  38.   
  39.     <script type="text/javascript">  
  40.         var ws = null;  
  41.         var url = null;  
  42.         var transports = [];  
  43.   
  44.         function setConnected(connected) {  
  45.             document.getElementById('connect').disabled = connected;  
  46.             document.getElementById('disconnect').disabled = !connected;  
  47.             document.getElementById('echo').disabled = !connected;  
  48.         }  
  49.   
  50.         function connect() {  
  51.             alert("url:"+url);  
  52.             if (!url) {  
  53.                 alert('Select whether to use W3C WebSocket or SockJS');  
  54.                 return;  
  55.             }  
  56.   
  57.             ws = (url.indexOf('sockjs') != -1) ?   
  58.                 new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);  
  59.   
  60.             ws.onopen = function () {  
  61.                 setConnected(true);  
  62.                 log('Info: connection opened.');  
  63.             };  
  64.             ws.onmessage = function (event) {  
  65.                 log('Received: ' + event.data);  
  66.             };  
  67.             ws.onclose = function (event) {  
  68.                 setConnected(false);  
  69.                 log('Info: connection closed.');  
  70.                 log(event);  
  71.             };  
  72.         }  
  73.   
  74.         function disconnect() {  
  75.             if (ws != null) {  
  76.                 ws.close();  
  77.                 ws = null;  
  78.             }  
  79.             setConnected(false);  
  80.         }  
  81.   
  82.         function echo() {  
  83.             if (ws != null) {  
  84.                 var message = document.getElementById('message').value;  
  85.                 log('Sent: ' + message);  
  86.                 ws.send(message);  
  87.             } else {  
  88.                 alert('connection not established, please connect.');  
  89.             }  
  90.         }  
  91.   
  92.         function updateUrl(urlPath) {  
  93.             if (urlPath.indexOf('sockjs') != -1) {  
  94.                 url = urlPath;  
  95.                 document.getElementById('sockJsTransportSelect').style.visibility = 'visible';  
  96.             }  
  97.             else {  
  98.               if (window.location.protocol == 'http:') {  
  99.                   url = 'ws://' + window.location.host + urlPath;  
  100.               } else {  
  101.                   url = 'wss://' + window.location.host + urlPath;  
  102.               }  
  103.               document.getElementById('sockJsTransportSelect').style.visibility = 'hidden';  
  104.             }  
  105.         }  
  106.   
  107.         function updateTransport(transport) {  
  108.             alert(transport);  
  109.           transports = (transport == 'all') ?  [] : [transport];  
  110.         }  
  111.           
  112.         function log(message) {  
  113.             var console = document.getElementById('console');  
  114.             var p = document.createElement('p');  
  115.             p.style.wordWrap = 'break-word';  
  116.             p.appendChild(document.createTextNode(message));  
  117.             console.appendChild(p);  
  118.             while (console.childNodes.length > 25) {  
  119.                 console.removeChild(console.firstChild);  
  120.             }  
  121.             console.scrollTop = console.scrollHeight;  
  122.         }  
  123.     </script>  
  124. </head>  
  125. <body>  
  126. <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets   
  127.     rely on Javascript being enabled. Please enable  
  128.     Javascript and reload this page!</h2></noscript>  
  129. <div>  
  130.     <div id="connect-container">  
  131.         <input id="radio1" type="radio" name="group1" onclick="updateUrl(''/spring-websocket-uptest/websocket');">  
  132.             <label for="radio1">W3C WebSocket</label>  
  133.         <br>  
  134.         <input id="radio2" type="radio" name="group1" onclick="updateUrl('/spring-websocket-uptest/websocket');">  
  135.             <label for="radio2">SockJS</label>  
  136.         <div id="sockJsTransportSelect" style="visibility:hidden;">  
  137.             <span>SockJS transport:</span>  
  138.             <select onchange="updateTransport(this.value)">  
  139.               <option value="all">all</option>  
  140.               <option value="websocket">websocket</option>  
  141.               <option value="xhr-polling">xhr-polling</option>  
  142.               <option value="jsonp-polling">jsonp-polling</option>  
  143.               <option value="xhr-streaming">xhr-streaming</option>  
  144.               <option value="iframe-eventsource">iframe-eventsource</option>  
  145.               <option value="iframe-htmlfile">iframe-htmlfile</option>  
  146.             </select>  
  147.         </div>  
  148.         <div>  
  149.             <button id="connect" onclick="connect();">Connect</button>  
  150.             <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>  
  151.         </div>  
  152.         <div>  
  153.             <textarea id="message" style="width: 350px">Here is a message!</textarea>  
  154.         </div>  
  155.         <div>  
  156.             <button id="echo" onclick="echo();" disabled="disabled">Echo message</button>  
  157.         </div>  
  158.     </div>  
  159.     <div id="console-container">  
  160.         <div id="console"></div>  
  161.     </div>  
  162. </div>  
  163. </body>  
  164. </html>  


  • 7  按照以上步骤搭建,根据个人开发环境不同,可能会出现各种问题,下面将在整个搭建过程中遇到的问题总结一下,详见博文:http://blog.csdn.net/gisredevelopment/article/details/38397569



演示实例增强版下载:spring-websocket-uptest.rar

尊重原创,转载请注明出处:

http://blog.csdn.net/gisredevelopment/article/details/38392629


技术邮箱,免费答疑:897658573@qq.com
0 0