spring websocket简单搭建
来源:互联网 发布:爱养成2圣灵之使数据 编辑:程序博客网 时间:2024/05/22 10:45
最近做项目用到web长连接所以用到 spring websocket。在spring中websocket的实现非常简单。
首先在spring项目中加入jar包spring-websocket包,或maven中加入
jar包版本根据自己spring版本决定
org.springframework
spring-websocket
${org.springframework-version}
/***spring websocket配置类*/@Configuration@EnableWebMvc@EnableWebSocketpublic class WebConfig implements WebSocketConfigurer { /** *路由处理 */ @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { //从ws://ip:端口/项目/echo 来的所有请求由 //simpleWebSocketHandler来处理 registry.addHandler(simpleWebSocketHandler(), "/echo"); } @Bean public SimpleWebSocketHandler simpleWebSocketHandler() { return new SimpleWebSocketHandler(); }}/***消息处理类*/public class SimpleWebSocketHandler implements WebSocketHandler { /** * 连接前处理 */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { //session.sendMessage(new TextMessage(JSON.toJSONString(""))); } /** * 消息处理 */ @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { System.out.println("消息处理 :" + message.getPayload()); session.sendMessage(new TextMessage("回复消息:" + message.getPayload())); } /** * 错误处理 */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { System.out.println("传输错误"); } /** * 连接关闭后处理事件 */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { System.out.println("连接关闭:"); } @Override public boolean supportsPartialMessages() { return false; }}
js代码
var URL = 'ws://' + window.location.host + "/test/echo";//创建一个Socket实例var ws = new WebSocket(URL);console.log(URL);ws.onopen = function(e) { console.info("打开连接");};ws.onmessage = function(e) { console.log(e.data);};ws.onclose = function() { // setConnected(false); console.log("连接关闭");};//消息发送ws.send("123");//*注意点:js端不能在加载页面后立即发送消息,否则会报异常(因为socket还在初始化中,没有建产连接)。在发送消息前应先判断连接状态。 if (ws.onopen) { console.log('已连接');}
1 0
- spring websocket简单搭建
- 利用spring-websocket包搭建websocket服务
- 使用spring-websocket包搭建websocket服务
- 利用spring-websocket包搭建websocket服务
- spring框架下搭建websocket
- Spring boot websocket简单例子
- 【JAVA-Spring】利用spring-websocket包来搭建websocket服务
- Spring boot WebSocket stomp简单例子
- websocket搭建
- Spring项目搭建【简单】
- 简单spring-mvc搭建
- 简单搭建spring mvc
- 简单Spring框架搭建
- 简单搭建Spring Hello
- Spring WebSocket
- spring websocket
- spring websocket
- WebSocket Spring
- MYSQL 区分大小写及乱码解决
- mysql 触发器
- php和c#一致的DES加密解密算法类
- webkit基础
- 用gdb调试程序笔记: 以段错误(Segmental fault)为例
- spring websocket简单搭建
- 2016蓝桥杯基础训练——十六进制转十进制
- iOS 原生网络请求写法
- 盘点8种CSS实现垂直居中水平居中的绝对定位居中技术
- PictureStudio开发笔记02-多国语言界面的实现
- UIGraphicsBeginImageContext和UIGraphicsBeginImageContextWithOptions实现iOS中的截图功能
- Maven入门--概念与实例
- JMS入门(三)--Queue的使用
- 我看BI在中国