以前作的需求都是客户端请求服务器响应,新需求是服务器主动推送信息到客户端.百度以后有流、长轮询、websoket等方式进行.可是目前更加推崇且合理的显然是websocket.
从springboot官网翻译了一些资料,再加上百度简单实现了springboot使用websocekt与客户端的双工通讯.html
<!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.0.4.RELEASE</version> </dependency>
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GlobalConfig { public static void main(String[] args) { SpringApplication.run(GlobalConfig.class, args); } }
正如springboot 官网推荐的websocket案例,须要实现WebSocketHandler或者继承TextWebSocketHandler/BinaryWebSocketHandler当中的任意一个.html5
package com.xiaoer.handler; import com.alibaba.fastjson.JSONObject; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.util.HashMap; import java.util.Map; /** * 至关于controller的处理器 */ public class MyHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); Map<String, String> map = JSONObject.parseObject(payload, HashMap.class); System.out.println("=====接受到的数据"+map); session.sendMessage(new TextMessage("服务器返回收到的信息," + payload)); } }
package com.xiaoer.config; import com.xiaoer.handler.MyHandler; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "myHandler/{ID}"); } public WebSocketHandler myHandler() { return new MyHandler(); } }
出现如上图是由于不能直接经过http协议访问,须要经过html5的ws://协议进行访问.java
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> var userID="888"; var websocket=null; $(function(){ connectWebSocket(); }) //创建WebSocket链接 function connectWebSocket(){ console.log("开始..."); //创建webSocket链接 websocket = new WebSocket("ws://127.0.0.1:8080/myHandler/ID="+userID); //打开webSokcet链接时,回调该函数 websocket.onopen = function () { console.log("onpen"); } //关闭webSocket链接时,回调该函数 websocket.onclose = function () { //关闭链接 console.log("onclose"); } //接收信息 websocket.onmessage = function (msg) { console.log(msg.data); } } //发送消息 function send(){ var postValue={}; postValue.id=userID; postValue.message=$("#text").val(); websocket.send(JSON.stringify(postValue)); } //关闭链接 function closeWebSocket(){ if(websocket != null) { websocket.close(); } } </script> </body> </html>
利用客户端运行以后仍然会出现上图中的一链接就中断了websocket链接.
这是由于spring默认不接受跨域访问:jquery
As of Spring Framework 4.1.5, the default behavior for WebSocket and SockJS is to accept only same origin requests.
须要在WebSocketConfig中设置setAllowedOrigins.web
package com.xiaoer.config; import com.xiaoer.handler.MyHandler; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "myHandler/{ID}") .setAllowedOrigins("*"); } public WebSocketHandler myHandler() { return new MyHandler(); } }
以下图,并未输出中断,说明链接成功.spring
服务器端收到消息
客户端收到服务器主动推送消息json
以上就是一个最基础的springboot简单应用.还能够经过拦截器、重写WebSocketConfigurer中的方法进行更为复杂的属性操做.具体能够参考SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送跨域