1、什么是websocket?

  WebSocket协议定义了一种web应用的新功能,它实现了服务器端和客户端的全双工通信。全双工通信即通信的双方可以同时发送和接收信息 的信息交互方式。它是继Java applets, XMLHttpRequest, Adobe Flash, ActiveXObject等使web应用更具交互性的新技术。

  在实现连线过程中,浏览器和服务器通过TCP三次握手建立连接。 如果和服务器连接成功后,浏览器通过HTTP发送握手请求,如果服务器同意握手连接,客户端和服务端之后就能互相之间发送信息。HTTP只用于开始的握手,一旦成功建立握手连接,HTTP不会参与数据传输,使用TCP连接来传输数据。

2、以往和服务器交互的几种方式

  轮询

  长轮询就是客户端按照一个固定的时间定期向服务器发送请求,通常这个时间间隔的长度受到服务端的更新频率和客户端处理更新数据时间的影响。这种方式缺点很明显,就是浏览器要不断发请求到服务器以获取最新信息,造成服务器压力过大,占用宽带资源。

    使用streaming AJAX

  streaming ajax是一种通过ajax实现的长连接维持机制。主要目的就是在数据传输过程中对返回的数据进行读取,并且不会关闭连接。

  iframe方式

  iframe可以在页面中嵌套一个子页面,通过将iframe的src指向一个长连接的请求地址,服务端就能不断往客户端传输数据。

3、什么时候用websocket?

  最适合websocket的web应用的就是那些客户端和服务器端需要高频繁、低延迟交换信息的应用。

4、如何使用websocket?

  Spring提供了一个是适应于各种websocket引擎的websocket api,例如是Tomcat (7.0.47+)和GlassFish (4.0+),也适应于支持原生websocket的Jetty (9.0+)。而不同的浏览器对websocket的支持程度也有所不同,如果浏览器websocket不支持,那么可以用SocketJs代替websocket。

  创建和配置WebSocketHandler

  WebSocketHandler用于处理websocket的消息。

public class MyHandler extends TextWebSocketHandler {

    @Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    session.sendMessage(message);
} }

创建和配置HandshakeInterceptor

HandshakeInterceptor用于处理握手前后的预处理工作。

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
System.out.println("After Handshake");
super.afterHandshake(request, response, wsHandler, ex);
} @Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Map<String, Object> attributes) throws Exception {
System.out.println("Before Handshake");
     return super.beforeHandshake(request, response, wsHandler, attributes);
}
}

同时配置spring-websocket.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd"> <websocket:handlers>
<websocket:mapping handler="myHandler" path="/myHandler"/>
<websocket:handshake-interceptors>
<bean class="org.springframework.samples.HandshakeInterceptor"></bean>
</websocket:handshake-interceptors>
</websocket:handlers>
<!--兼容低版本浏览器-->
<websocket:handlers>
<websocket:mapping handler="myHandler" path="/js/myHandler"/>
<websocket:handshake-interceptors>
<bean class="org.springframework.samples.HandshakeInterceptor"></bean>
</websocket:handshake-interceptors>
<websocket:sockjs />
</websocket:handlers> <bean id="myHandler" class="org.springframework.samples.MyHandler"></bean> </beans>

在页面上添加JavaScript

<script type="text/javascript" src="js/sockjs.min.js"></script>
<script type="text/javascript">
  //websocket-demo是project name
var sock=null;
if (window['WebSocket']) {
sock= new WebSocket('ws://' + window.location.host+'/websocket-demo/myHandler');
}
else
sock= new SockJS('/websocket-demo/js/myHandler');//兼容低版本浏览器
sock.onopen = function() {
console.log('Opening');
sayHello();
};
sock.onmessage = function(e) {
alert('Received message: '+ e.data);
};
sock.onclose = function() {
console.log('Closing');
};
function sayHello() {
console.log('Sending Hello!');
sock.send("Hello!");
}
</script>

如果要兼容低版本浏览器,还要在web.xml添加

<async-supported>true</async-supported>

需要注意的地方:

1、应用服务器的版本,如果版本过低是不支持websocket的

2、JavaScript的websocket的url应该和spring-websocket.xml的<websocket:mapping path="">一致

3、要兼容低版本浏览器,要使用web3.0,还有必须在一个请求涉及的所有Servlet及Filter中都声明asyncSupported=true。

下载:websocket-demo

学习WebSocket(一):Spring WebSocket的简单使用的更多相关文章

  1. 谈一谈Tomcat中webSocket,Jetty WebSocket 和Spring WebSocket以及github中Java-WebSocket.jar分别对Socket协议的角色定位以及效果的不同点;

    开局先上一张图:(http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html)   当前截图来自于apache的tomcat官网(问:为 ...

  2. Spring 学习——基于Spring WebSocket 和STOMP实现简单的聊天功能

    本篇主要讲解如何使用Spring websocket 和STOMP搭建一个简单的聊天功能项目,里面使用到的技术,如websocket和STOMP等会简单介绍,不会太深,如果对相关介绍不是很了解的,请自 ...

  3. spring websocket集群问题的简单记录

    目录 前言 解决方案 代码示例 前言 最近公司里遇到一个问题,在集群中一些websocket的消息丢失了. 产生问题的原理很简单,发送消息的服务和接收者连接的服务不是同一个服务. 解决方案 用中间件( ...

  4. WebSocket 学习教程(二):Spring websocket实现消息推送

    =============================================== 环境介绍: Jdk 1.7 (1.6不支持) Tomcat7.0.52 (支持Websocket协议) ...

  5. spring WebSocket详解

    场景 websocket是Html5新增加特性之一,目的是浏览器与服务端建立全双工的通信方式,解决http请求-响应带来过多的资源消耗,同时对特殊场景应用提供了全新的实现方式,比如聊天.股票交易.游戏 ...

  6. spring websocket源码分析

    什么是websocket? 摘录于wiki[1]: WebSocket is a protocol providing full-duplex communication channels over ...

  7. Spring WebSocket初探2 (Spring WebSocket入门教程)<转>

    See more: Spring WebSocket reference整个例子属于WiseMenuFrameWork的一部分,可以将整个项目Clone下来,如果朋友们有需求,我可以整理一个独立的de ...

  8. Spring WebSocket初探1 (Spring WebSocket入门教程)<转>

    See more: Spring WebSocket reference整个例子属于WiseMenuFrameWork的一部分,可以将整个项目Clone下来,如果朋友们有需求,我可以整理一个独立的de ...

  9. Spring WebSocket教程(二)

    实现目标 这一篇文章,就要直接实现聊天的功能,并且,在聊天功能的基础上,再实现缓存一定聊天记录的功能. 第一步:聊天实现原理 首先,需要明确我们的需求.通常,网页上的聊天,都是聊天室的形式,所以,这个 ...

随机推荐

  1. nodejs里的module.exports和exports的关系

    关于node里面的module.exports和exports的异同,网上已经有很多的资料,很多的文章,很多的博客,看了很多,好像懂了,又好像不懂,过几天又不懂了...大致总结是这样的: //下面这种 ...

  2. Mysql数据库之Binlog日志使用总结

    binlog二进制日志对于mysql数据库的重要性有多大,在此就不多说了.下面根据本人的日常操作经历,并结合网上参考资料,对binlog日志使用做一梳理: 一.binlog日志介绍1)什么是binlo ...

  3. Java 日志性能优化

    1. 选择合理的日志级别.合理控制日志内容 2. 控制日志的输出内容和格式 logger.debug("Entry number: " + i + " is " ...

  4. win7登录后开机密码破解读取

    在win7登录后,win7密码可以直接读取. https://github.com/gentilkiwi/mimikatz

  5. 前端面试——css篇

    css盒子模型 在W3C模型中: 总宽度 = margin-left + border-left + padding-left + width + padding-right + border-rig ...

  6. Power of Two

    Given an integer, write a function to determine if it is a power of two. bool isPowerOfTwo(int n) { ...

  7. tkinter 类继承的三种方式

    tkinter class继承有三种方式. 提醒注意这几种继承的运行方式 一.继承 object 1.铺tk.Frame给parent: 说明: self.rootframe = tk.Frame(p ...

  8. docker 镜像导入导出

    导出(Export) Export命令用于持久化容器(不是镜像).所以,我们就需要通过以下方法得到容器ID: sudo docker ps -a 接着执行导出: sudo docker export ...

  9. web安全——数据库(mysql)

    简介 数据安全是现在互联网安全非常重要一个环节.而且一旦数据出现问题是不可逆的,甚至是灾难性的. 有一些防护措施应该在前面几个博文说过了,就不再赘述.比如通过防火墙控制,通过系统的用户控制,通过web ...

  10. MVC认知路【点点滴滴支离破碎】【一】----新建数据库

    1.App_Data文件夹创建[SQL Server Compact Local Database *]数据库 2.添加链接字符串<add name="MovieDBContext&q ...