博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot 集成 websocket
阅读量:7242 次
发布时间:2019-06-29

本文共 7952 字,大约阅读时间需要 26 分钟。

hot3.png

pom.xml

4.0.0
springws
springws
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.5.3.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-maven-plugin

application.properties

server.port=8080###########################################################THYMELEAF (ThymeleafAutoConfiguration)#########################################################spring.thymeleaf.prefix=classpath:/templates/#spring.thymeleaf.suffix=.html#spring.thymeleaf.mode=HTML5#spring.thymeleaf.encoding=UTF-8# ;charset=
is added# spring.thymeleaf.content-type=text/html# set to false for hot refreshspring.thymeleaf.cache=falsedebug=true###########spring.datasource.url=jdbc:mysql://localhost:3306/ccvms#spring.datasource.username=root#spring.datasource.password=root#spring.datasource.driver-class-name=com.mysql.jdbc.Driver#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect#spring.jpa.hibernate.ddl-auto=none#spring.jpa.show-sql=true#spring.jackson.serialization.indent-output=true

创建 config

package com.ws.util;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {    @Bean    public ServerEndpointExporter serverEndpointExporter(ApplicationContext context) {        return new ServerEndpointExporter();    }    @Override    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {        registry.addHandler(new CountWebSocketHandler(), "/web/count.do").addInterceptors(new HandshakeInterceptor());    }}

创建拦截器

package com.ws.util;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;import java.util.Map;public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {    @Override    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,                                   Map
attributes) throws Exception { //解决The extension [x-webkit-deflate-frame] is not supported问题 if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) { request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate"); } System.out.println("Before Handshake"); return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { System.out.println("After Handshake"); super.afterHandshake(request, response, wsHandler, ex); }}

创建处理器

package com.ws.util;import org.springframework.stereotype.Component;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;import java.io.IOException;import java.util.*;@Componentpublic class CountWebSocketHandler extends TextWebSocketHandler {    private static Map
sessionMap = new HashMap<>(); @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// session.sendMessage(new TextMessage(session.getPrincipal().getName()+",你是第" + (sessionMap.size()) + "位访客")); //p2p if(message.getPayload().equals("ping")) { sendMessage(session.getId(),"pong"+session.getId()); return; }else { //处理正常的对话 } } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionMap.put(session.getId(),session); sendMessage(session.getId(), "welcome to connect"); super.afterConnectionEstablished(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessionMap.remove(session.getId()); super.afterConnectionClosed(session, status); } /** * 发送消息 * 单发 */ public static void sendMessage(String username,String message) throws IOException { sendMessage(Arrays.asList(username),Arrays.asList(message)); } /** * * 发送消息 * 群发 */ public static void sendMessage(Collection
acceptorList,String message) throws IOException { sendMessage(acceptorList,Arrays.asList(message)); } /** * 发送消息,p2p 群发都支持 */ public static void sendMessage(Collection
acceptorList, Collection
msgList) throws IOException { if (acceptorList != null && msgList != null) { for (String acceptor : acceptorList) { WebSocketSession session = sessionMap.get(acceptor); if (session != null && session.isOpen() ) { for (String msg : msgList) { session.sendMessage(new TextMessage(msg.getBytes())); } } } } } /** 群发/推送 **/ public static void sendToAll() throws IOException { sendMessage(sessionMap.keySet(), " this is from web "); }}

启动类

package com.ws;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App {    public static void main(String ... args){        SpringApplication.run(App.class,args);    }}

html测试

打开console查看

Insert title here

服务器端推送

package com.ws.controller;import java.io.IOException;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import com.ws.util.CountWebSocketHandler;@RestControllerpublic class IndexController {    @GetMapping("/push")    public String index() throws IOException{    	CountWebSocketHandler.sendToAll();    	return "success";      }}

转载于:https://my.oschina.net/u/2528821/blog/1623470

你可能感兴趣的文章
CocoaAsyncSocket学习
查看>>
关于form.item不兼容的问题
查看>>
poj Supermarket
查看>>
常用变量的获取
查看>>
洛谷9月月赛round2
查看>>
Lazy的SDL教程 翻译----Lesson 22 Timing
查看>>
C#调用带输出参数的mysql存储过程
查看>>
两个序列中位数算法c语言,PAT 2-13 两个有序序列的中位数(C语言实现)
查看>>
android 上下左右滑动的表格,适用小程序的表格table,冻结行,冻结列,可左右,上下滑动...
查看>>
HTML表单滚动文本框,table表格,form表单,select下拉列表,textarea文本域
查看>>
【原创】mysql 错误缓冲堆栈
查看>>
SystemCenter2012SP1实践(25)VMM下HyperV的高可用(上)
查看>>
oracle vm的虚拟机windows启动不了的处理方式
查看>>
Hyper-V 2012实时迁移
查看>>
Microsoft Azure Site Recovery (2) 配置虚拟机保护
查看>>
Microsoft Azure Site Recovery (1) 安装VMM服务器代理
查看>>
【转】动态模型及其求解介绍—上
查看>>
学习 ExtJS 4 面板与布局
查看>>
SQL ALTER TABLE 语句
查看>>
使用jquery提交form表单并自定义action
查看>>