springBoot 搭建websocke 实现群聊,点对点聊天等开发
这几天研究JAVA的springBoot,顺便把websocket也搭建了,发现网上相关文档较下,参考网上资料,与自己的想法,写下以下搭建方法以做方便查看
1、依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<!-- websocket -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
2、添加websocket配置类WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、WebSocket类
package com.projuct.junlaishun.Controller.websocket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 前后端交互的类实现消息的接收推送
*
* @ServerEndpoint(value = "/ws/{userId}") 前端通过此URI 和后端交互,建立连接,userId为用户id
*/
@Slf4j
@ServerEndpoint(value = "/ws/{userId}")
@Component
public class WebSocket {
private Map<String,Integer> NAMES;
/** 记录当前在线连接数 */
private static AtomicInteger onlineCount = new AtomicInteger(0);
/** 存放所有在线的客户端 */
private static Map<String, Session> clients = new ConcurrentHashMap<>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId) {
onlineCount.incrementAndGet(); // 在线数加1
clients.put(userId, session);
log.info("有新连接加入:{},当前在线人数为:{},用户id:{}", session.getId(), onlineCount.get(),userId);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session,@PathParam("userId") String userId) {
onlineCount.decrementAndGet(); // 在线数减1
clients.remove(userId);
log.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
* 这里能过地址获取用户userId与ws session关联至map中
*/
@OnMessage
public void onMessage(String message, Session session,@PathParam("userId") String userId) {
log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
try {
JSONObject myMessage = JSON.parseObject(message);
if (myMessage != null) {
Session toSession = null;
if(myMessage.getString("userId") != null){
toSession = clients.get(myMessage.getString("userId")); //取到接收userId session
}
if (toSession != null) {
this.sendMessage(myMessage.get("message").toString(), toSession);
}else{
log.info("type:"+myMessage.getString("type"));
if (myMessage.getString("type").equals("all")){
//群发
this.sendMessageAll(myMessage.get("message").toString(),userId);
}else{
log.error("session不存在");
}
}
}
} catch (Exception e) {
log.error("解析失败:{}", e);
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 服务端发送消息给客户端
*/
private void sendMessage(String message, Session toSession) {
try {
log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
toSession.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("服务端发送消息给客户端失败:{}", e);
}
}
/**
* 群发消息
*
* @param message
* 消息内容
*/
private void sendMessageAll(String message, String userId) {
for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
Session toSession = sessionEntry.getValue();
// 排除掉自己
if (!userId.equals(sessionEntry.getKey())) {
//log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
log.info("服务端给客户端用户id:[{}]发送消息{}", userId, message);
toSession.getAsyncRemote().sendText(message);
}
}
}
}
4、前端测试
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket Demo</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">发送</button>
<button onclick="closeWebSocket()">关闭</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket, 更换为自己的地址
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8881/ws/3"); //3为测试用户id
} 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>

浙公网安备 33010602011771号