一、项目介绍
用springboot实现服务端(后台)想前端发送消息通知
二、项目背景
假设有一个用户前往医院找专家看病的场景,一个专家对应多个用户,当第一个用户看病结束后通知第二用户前往房间,
传统的模式都是服务端发起请求,服务端响应请求,返回数据给我客户端。考虑到 socket是一个全双工的协议,既可以是客户端也
可以是服务端,于是选择了WebSocket.
三、项目目录结构
四、项目代码
---------------------------------项目环境依赖---------------------------------------
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-websocket
org.projectlombok
lombok
true
----------------------Controller层-----------------------------------
package com.gpdi.controller;
import com.gpdi.config.WebSocket;
import com.gpdi.util.ResponseData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.io.IOException;
/**
* @desc: 用Socket实现服务端到客户端消息的单发和群发
*/
@Controller
public class SocketController {
/**
* @desc: 向所有人发送消息
*/
@RequestMapping("sendToAll")
@ResponseBody
public ResponseData sendToAll() {
webSocket.sendMessage("服务端向客户端消息群发!");
return new ResponseData(200, "群发请求成功");
}
/**
* @desc: 向某个人发送消息
*/
@RequestMapping("sendToOne")
@ResponseBody
public ResponseData sendToOne(String sessionId) throws IOException {
webSocket.sendMessage(sessionId, "向SessionId为" + sessionId + "的用户发送消息通知");
return new ResponseData(200, "单发请求成功", sessionId);
}
@Resource
WebSocket webSocket;
}
--------------------------------WebSocket配置文件---------------------------
package com.gpdi.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint(value = "/webSocket")
@Slf4j
public class WebSocket {
//每个客户端都会有相应的session,服务端可以发送相关消息
private Session session;
private static CopyOnWriteArraySet copyOnWriteArraySet = new CopyOnWriteArraySet();
//存储userId和SessionId
private Map map = new ConcurrentHashMap<>();
/**
* 打开连接。进入页面后会自动发请求到此进行连接
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
String sessionUrl = session.getRequestURI().toString();
String username = sessionUrl.substring(sessionUrl.indexOf("="), sessionUrl.length()).substring(1);
map.put(username, session.getId());
System.out.println("以下是最新的遍历结果");
map.keySet().forEach((a) -> {
System.out.println("用户为" + a + "用户的SessionID为" + map.get(a));
});
this.session = session;
copyOnWriteArraySet.add(this);
log.info("websocket有新的连接, 总数:" + copyOnWriteArraySet.size());
}
/**
* 用户关闭页面,即关闭连接
*/
@OnClose
public void onClose() {
copyOnWriteArraySet.remove(this);
log.info("webSocket连接断开, 总数:" + copyOnWriteArraySet.size());
}
/**
* 测试客户端发送消息,测试是否联通
*
* @param message
*/
@OnMessage
public void onMessage(String message) {
log.info("websocket收到客户端发来的消息:" + message);
}
/**
* 出现错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:" + error.getMessage(), session.getId());
error.printStackTrace();
}
/**
* 用于发送给客户端消息(群发)
*
* @param message
*/
public void sendMessage(String message) {
//遍历客户端
for (WebSocket webSocket : copyOnWriteArraySet) {
log.info("websocket广播消息:" + message);
try {
//服务器主动推送
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 用于发送给指定客户端消息
*
* @param message
*/
public void sendMessage(String sessionId, String message) throws IOException {
//这里有一个Session,最外面还有一个全局Session
Session session = null;
WebSocket tempWebSocket = null;
for (WebSocket webSocket : copyOnWriteArraySet) {
if (webSocket.session.getId().equals(sessionId)) {
tempWebSocket = webSocket;
session = webSocket.session;
break;
}
}
if (session != null) {
tempWebSocket.session.getBasicRemote().sendText(message);
} else {
log.warn("没有找到你指定ID的会话:{}", sessionId);
}
}
/**
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
----------------------------------工具包------------------------------------
package com.gpdi.util;
/**
*
* @desc:封装自定义返回数据工具类
*
*/
public class ResponseData {
private int state;
private String msg;
private Object object;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public ResponseData(int state, String msg) {
this.state = state;
this.msg = msg;
}
public ResponseData() {
}
public ResponseData(int state, String msg, Object object) {
this.state = state;
this.msg = msg;
this.object = object;
}
}
----------------------------------启动文件-------------------
package com.gpdi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
------------------------------------- 系统页面---------------------------
Title
当前页面为Socket客户端