Springboot集成WebSocket简单开发(前端到后台)

1.引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.开启websocket支持端点

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

3.创建server核心类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Class: WebSocketServer
* @Description: 连接、消息管理
*/
@ServerEndpoint("/ws/{userId}")
@Component
public class WebSocketServer {
//日志
static Log log = LogFactory.getLog(WebSocketServer.class);
//在线数量
private static final AtomicInteger onlineCount = new AtomicInteger(0);
//处理客户端连接socket
private static Map<String, WebSocketServer> webSocketMap = new
ConcurrentHashMap<>();
//会话信息
private Session session;
//用户信息
private String userId = "";
/*
* @Description: 打开WebSokcet连接
* @Method: onOPen
* @Param: [userId, session]
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
@OnOpen
public void onOPen(@PathParam("userId") String userId, Session session) {
//处理session和用户信息
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
} else {
webSocketMap.put(userId, this);
//增加在线人数
addOnlineCount();
}
try {
//处理连接成功消息的发送
sendMessage("Server>>>>远程WebSoket连接成功");
log.info("用户" + userId + "成功连接,当前的在线人数为" +
getOnlineCount());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* @Description: 关闭连接
* @Method: onClose
* @Param: []
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
subOnlineCount();
}
log.info("用户退出....");
}
public static void subOnlineCount() {
WebSocketServer.onlineCount.decrementAndGet();
}
/*
* @Description:消息中转
* @Method: onMessage
* @Param: [message, session]
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
@OnMessage
public void onMessage(String message, Session session) {
if (StringUtils.isNotEmpty(message)) {
try {
//解析消息
JSONObject jsonObject = JSON.parseObject(message);
String toUserId = jsonObject.getString("toUserId");
String msg = jsonObject.getString("msg");
if (StringUtils.isNotEmpty(toUserId)&&webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* @Description: 服务端向客户端发送数据
* @Method: sendMessage
* @Param: [s]
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
public void sendMessage(String s) throws IOException {
this.session.getBasicRemote().sendText(s);
}
/*
* @Description: 获取在线人数的数量
* @Method: getOnlineCount
* @Param: []
* @Update:
* @since: 1.0.0
* @Return: java.util.concurrent.atomic.AtomicInteger
*
*/
public static AtomicInteger getOnlineCount() {
return onlineCount;
}
/*
* @Description: 增加在线人数
* @Method: addOnlineCount
* @Param: []
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
public static void addOnlineCount() {
WebSocketServer.onlineCount.incrementAndGet();
}
/*
* @Description: 服务器消息推送
* @Method: sendInfo
* @Param: [message, userId]
* @Update:
* @since: 1.0.0
* @Return: void
*
*/
public static boolean sendInfo(String message, @PathParam("userId") String
userId) throws IOException {
boolean flag=true;
if (StringUtils.isNotEmpty(userId) && webSocketMap.containsKey(userId))
{
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("用户" + userId + "不在线");
flag=false;
}
return flag;
}
}

4.创建控制器

@RequestMapping("im")
public ModelAndView page() {
return new ModelAndView("ws");
}
/*
* @Description: 消息推送
* @Method: pushToWeb
* @Param: [message, toUserId]
* @Update:
* @since: 1.0.0
* @Return: org.springframework.http.ResponseEntity<java.lang.String>
*
*/
@RequestMapping("/push/{toUserId}")
public ResponseEntity<String> pushToWeb(String message, @PathVariable String
toUserId) throws Exception {
boolean flag = WebSocketServer.sendInfo(message, toUserId);
return flag == true ? ResponseEntity.ok("消息推送成功...") :
ResponseEntity.ok("消息推送失败,用户不在线...");
}

5.创建html页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="../css/index.css" rel="stylesheet">
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
function openWebSocket() {
if (typeof(WebSocket) == "undefined") {
console.log("对不起,您的浏览器不支持WebSocket");
} else {
var webSocketUrl = "ws://localhost:9999/ws/im/" +
$("#userId").val();
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(webSocketUrl);
//打开
socket.onopen = function () {
console.log("Client>>>>WebSocket已打开");
};
//获取消息
socket.onmessage = function (msg) {
console.log(msg.data);
$("#msg").val(msg.data)
};
//关闭
socket.onclose = function () {
console.log("Client>>>>WebSocket已关闭");
};
//发生错误
socket.onerror = function () {
console.log("Client>>>>WebSocket发生了错误");
}
}
}
function sendMessage() {
if (typeof(WebSocket) == "undefined") {
console.log("对不起,您的浏览器不支持WebSocket");
} else {
socket.send('{"toUserId":"' + $("#toUserId").val() + '","msg":"' +
$("#msg").val() + '"}');
}
}
</script>
<body>
<div id="panel">
<div class="panel-header">
<h2>即时通讯IM</h2>
</div>
<div class="panel-content">
<div class="user-pwd">
<button class="btn-user"></button>
<input id="userId" name="userId" type="text" value="张三">
</div>
<div class="user-pwd">
<button class="btn-user"></button>
<input id="toUserId" name="toUserId" type="text" value="李四">
</div>
<div class="user-msg">
<input id="msg" name="msg" type="text" value="">
</div>
<div class="panel-footer">

<button class="login-btn" onclick="openWebSocket()" >连接
WebSocket</button>
<button class="login-btn" onclick="sendMessage()">发送消息</button>
</div>
</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值