Springboot websocket学习Demo
使用的是springboot2.1.4版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
要使用websocket需要一个Bean,否则报错Error during WebSocket handshake:之类的问题
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
后端代码WebSocketServer.java
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @ServerEndpoint("/imserver/{userId}")
@Component
@Slf4j
public class WebSocketServer { /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
private static int onlineCount = 0;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**接收userId*/
private String userId=""; public WebSocketServer() {
log.info(this.toString());
} /**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId) {
this.session = session;
this.userId=userId;
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
webSocketMap.put(userId,this);
//加入set中
}else{
webSocketMap.put(userId,this);
//加入set中
addOnlineCount();
//在线数加1
} log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount()); try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+userId+",网络异常!!!!!!");
}
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:"+userId+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(isNotBlank(message)){
try {
//解析发送的报文
String toUserId = this.userId + "";
log.info(this.userId + ", msg = " + message);
webSocketMap.get(toUserId).sendMessage(message);
}catch (Exception e){
e.printStackTrace();
}
}
} private static boolean isNotBlank(String str){
return str!=null && !str.equals("");
} /**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
} /**
* 发送自定义消息
* */
public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
log.info("发送消息到:"+userId+",报文:"+message);
if(isNotBlank(userId)&&webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(message);
}else{
log.error("用户"+userId+",不在线!");
}
} public static synchronized int getOnlineCount() {
return onlineCount;
} public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
} public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
前端代码index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script>
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/demo/imserver/11");
}
else {
alert('当前浏览器 Not support websocket')
} //连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
}; //连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
} //接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
} //连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
} //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
} //将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
} //关闭WebSocket连接
function closeWebSocket() {
websocket.close();
} //发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script> </html>
后面是我的总结,如果有什么地方不对的,请留言:

Springboot websocket学习Demo的更多相关文章
- WebSocket 学习(三)--用nodejs搭建服务器
前面已经学习了WebSocket API,包括事件.方法和属性.详情:WebSocket(二)--API WebSocket是基于事件驱动,支持全双工通信.下面通过三个简单例子体验一下. 简单开始 ...
- (转)WebSocket学习
石墨文档:https://shimo.im/docs/3UkyOPJvmj4f9EAP/ (二期)17.即时通讯技术websocket [课程17]java We...实现.xmind0.1MB [课 ...
- WebSocket 学习--用nodejs搭建服务器
最简单的socket服务端 var net = require("net"); server1 = net.createServer(function(client){ clien ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...
- 基于SpringBoot+WebSocket搭建一个简单的多人聊天系统
前言 今天闲来无事,就来了解一下WebSocket协议.来简单了解一下吧. WebSocket是什么 首先了解一下WebSocket是什么?WebSocket是一种在单个TCP连接上进行全双工 ...
- MacOS下SpringBoot基础学习
学于黑马和传智播客联合做的教学项目 感谢 黑马官网 传智播客官网 微信搜索"艺术行者",关注并回复关键词"springboot"获取视频和教程资料! b站在线视 ...
- Springboot+Websocket+JWT实现的即时通讯模块
场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. 涉及技术栈 ...
- WebSocket学习笔记IE,IOS,Android等设备的兼容性问
WebSocket学习笔记IE,IOS,Android等设备的兼容性问 一.背景 公司最近准备将一套产品放到Andriod和IOS上面去,为了统一应用的开发方式,决定用各平台APP嵌套一个HTML5浏 ...
- WebSocket学习笔记——无痛入门
WebSocket学习笔记——无痛入门 标签: websocket 2014-04-09 22:05 4987人阅读 评论(1) 收藏 举报 分类: 物联网学习笔记(37) 版权声明:本文为博主原 ...
随机推荐
- K最邻近分类
最邻近分类是分类方法中比较简单的一种,下面对其进行介绍 1.模型结构说明 最邻近分类模型属于"基于记忆"的非参数局部模型,这种模型并不是立即利用训练数据建立模型,数据 ...
- if __name__ == "__main__"的疑惑
Python中if __name__ == "__main__"详细解释: 想必很多初次接触python都会见到这样一个语句,if __name__ == "__main ...
- Spring Cloud配置中心之Consul
Consul不仅可以作为Spring Cloud中服务的注册中心,也可以作为其配置中心,这样一个系统就可以实现服务发现和统一配置,减少系统维护的麻烦,其中在使用Consul作为配置中心使用的过程中可以 ...
- 关于Camtasia2020安装完成之后无法运行问题的解决方法
在录像编辑软件Cmtasia更新到了2020版本之后,有部分小伙伴们遇到了这样的问题:在我们安装好软件之后,居然无法运行.今天小编就给大家介绍一下该如何解决这个问题. 方法一: 第一步,选中桌面上Ca ...
- guitar pro系列教程(二十六):Guitar Pro教程之虚拟吉他功能讲解
上一章节我们讲述了Guitar Pro的组织小节的相关功能,那么本章节我们还是采用图文结合的方式为大家讲解关于guitar pro中一些虚拟的吉他功能一 一做出讲解,感兴趣的朋友可以一起进来学习了解哦 ...
- F - LCS 题解(最长公共子序列记录路径)
题目链接 题目大意 给你两个字符串,任意写出一个最长公共子序列 字符串长度小于3e3 题目思路 就是一个记录路径有一点要注意 找了好久的bug 不能直接\(dp[i][j]=dp[i-1][j-1]+ ...
- Java蓝桥杯练习题——Huffman树
Huffman树在编码中有着广泛的应用.在这里,我们只关心Huffman树的构造过程. 给出一列数{pi}={p0, p1, -, pn-1},用这列数构造Huffman树的过程如下: 找到{pi}中 ...
- 用Python爬取英雄联盟(lol)全部皮肤
小三:"怎么了小二?一副无精打采的样子!" 小二:"唉!别提了,还不是最近又接触了一个叫英雄联盟的游戏,游戏中很多皮肤都需要花钱买,但是我钱不够呀..." 小三 ...
- 14_TTS
TTS(Text to speech)为语音合成的意思.本课程主要介绍了TTS的使用方法. 1 package cn.eoe.tts; 2 3 import java.util.Locale; 4 i ...
- CBV装饰校验的三种方式session
代码如下: from django.shortcuts import render,HttpResponse,redirect from django.views import View # Crea ...