spting boot集成websorck
程序员文章站
2022-05-01 16:29:07
...
后端代码
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
如果spring去除了tomcat加入以下代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--去除内置tomcat-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 移除之后会报错,加入下面的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
核心代码
package com.demo.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author:JCccc
* @Description:
* @Date: created in 15:56 2019/5/13
*/
@Component
@ServerEndpoint(value = "/connectWebSocket/{userId}")
public class WebSocket {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 在线人数
*/
public static int onlineNumber = 0;
/**
* 以用户的姓名为key,WebSocket为对象保存起来
*/
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
/**
* 会话
*/
private Session session;
/**
* 用户名称
*/
private String userId;
/**
* 建立连接
*
* @param session
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session)
{
onlineNumber++;
logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+userId);
this.userId = userId;
this.session = session;
// logger.info("有新连接加入! 当前在线人数" + onlineNumber);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
//先给所有人发送通知,说我上线了
Map<String,Object> map1 = Maps.newHashMap();
map1.put("messageType",1);
map1.put("userId",userId);
sendMessageAll(JSON.toJSONString(map1),userId);
//把自己的信息加入到map当中去
clients.put(userId, this);
logger.info("有连接关闭! 当前在线人数" + clients.size());
//给自己发一条消息:告诉自己现在都有谁在线
Map<String,Object> map2 = Maps.newHashMap();
map2.put("messageType",3);
//移除掉自己
Set<String> set = clients.keySet();
map2.put("onlineUsers",set);
sendMessageTo(JSON.toJSONString(map2),userId);
}
catch (IOException e){
logger.info(userId+"上线的时候通知所有人发生了错误");
}
}
@OnError
public void onError(Session session, Throwable error) {
logger.info("服务端发生了错误"+error.getMessage());
//error.printStackTrace();
}
/**
* 连接关闭
*/
@OnClose
public void onClose()
{
onlineNumber--;
//webSockets.remove(this);
clients.remove(userId);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map<String,Object> map1 = Maps.newHashMap();
map1.put("messageType",2);
map1.put("onlineUsers",clients.keySet());
map1.put("userId",userId);
sendMessageAll(JSON.toJSONString(map1),userId);
}
catch (IOException e){
logger.info(userId+"下线的时候通知所有人发生了错误");
}
//logger.info("有连接关闭! 当前在线人数" + onlineNumber);
logger.info("有连接关闭! 当前在线人数" + clients.size());
}
/**
* 收到客户端的消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session)
{
try {
logger.info("来自客户端消息:" + message+"客户端的id是:"+session.getId());
System.out.println("------------ :"+message);
JSONObject jsonObject = JSON.parseObject(message);
String textMessage = jsonObject.getString("message");
String fromuserId = jsonObject.getString("userId");
String touserId = jsonObject.getString("to");
//如果不是发给所有,那么就发给某一个人
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map<String,Object> map1 = Maps.newHashMap();
map1.put("messageType",4);
map1.put("textMessage",textMessage);
map1.put("fromuserId",fromuserId);
if(touserId.equals("All")){
map1.put("touserId","所有人");
sendMessageAll(JSON.toJSONString(map1),fromuserId);
}
else{
map1.put("touserId",touserId);
System.out.println("开始推送消息给"+touserId);
sendMessageTo(JSON.toJSONString(map1),touserId);
}
}
catch (Exception e){
e.printStackTrace();
logger.info("发生了错误了");
}
}
public void sendMessageTo(String message, String TouserId) throws IOException {
for (WebSocket item : clients.values()) {
// System.out.println("在线人员名单 :"+item.userId.toString());
if (item.userId.equals(TouserId) ) {
item.session.getAsyncRemote().sendText(message);
break;
}
}
}
public void sendMessageAll(String message,String FromuserId) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineNumber;
}
}
配置类
package com.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
* @author zhengkai.blog.csdn.net
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
前端代码
<!DOCTYPE HTML>
<html>
<head>
<title>Test My WebSocket</title>
</head>
<body>
TestWebSocket
<input id="text" type="text" />
<button onclick="send()">SEND MESSAGE</button>
<button onclick="closeWebSocket()">CLOSE</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
//连接WebSocket节点
websocket = new WebSocket("ws://localhost:8071/connectWebSocket/002");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
下一篇: thinkphp中RBAC的有关问题
推荐阅读
-
【Swagger】可能是目前最好的 Spring Boot 集成 swagger 的方案
-
Spring Boot集成Mybatis的实例代码(简洁版)
-
spring boot 与kafka集成的示例代码
-
spring boot2.0.4集成druid,用jmeter并发测试工具调用接口,druid查看监控的结果
-
Spring boot 集成 Druid 数据源过程详解
-
Spring Boot集成Kafka的示例代码
-
使用Spring Boot集成FastDFS的示例代码
-
Spring Boot与Spark、Cassandra系统集成开发示例
-
spring boot 2 集成JWT实现api接口认证
-
Spring Boot 入门(五):集成 AOP 进行日志管理