1.配置依赖
org.springframework.boot
spring-boot-starter-websocket
2、配置类
package com.vim.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、消息类别
package com.vim.common.push;
public class WebSocketMsg {
public enum MsgType{
ONLINE_COUNT, NOTIFY;
}
/**
* 消息类型
*/
private MsgType type;
/**
* 消息内容
*/
private Object data;
public WebSocketMsg(MsgType type, Object data) {
this.type = type;
this.data = data;
}
public MsgType getType() {
return type;
}
public void setType(MsgType type) {
this.type = type;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
4、消息服务器
package com.vim.common.push;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicLong;
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {
private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
private Session session;
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 在线人数
*/
private static AtomicLong onlineCount = new AtomicLong(0);
/**
* 客户端集合
*/
private static HashSet servers = new HashSet<>();
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
boolean online = false;
for(WebSocketServer server:servers){
if(server.getUserId().equals(userId)){
online = true;
}
}
if(!servers.contains(this) && !online){
servers.add(this);
onlineCount.incrementAndGet();
sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));
}
}
@OnClose
public void onClose() {
servers.remove(this);
onlineCount.decrementAndGet();
sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));
}
/**
* 发送消息到指定用户
*/
public static void sendMessage(WebSocketMsg message, String userId) {
for (WebSocketServer server : servers) {
try {
if(server.getUserId().equals(userId)){
server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));
}
} catch (Exception e) {
logger.error("系统异常!", e);
}
}
}
/**
* 群发消息
*/
public static void sendMessage(WebSocketMsg message) {
for (WebSocketServer server : servers) {
try {
server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));
} catch (Exception e) {
logger.error("系统异常!", e);
}
}
}
}
5、html代码
通用项目模板var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://"+window.location.host+"/websocket/11");
}
websocket.onopen = onOpen;
websocket.onmessage = onMessage;
websocket.onerror = one rror;
websocket.onclose = onClose;
function onMessage(event) {
var result = JSON.parse(event.data);
if(result.type == "ONLINE_COUNT"){
}
if(result.type == "NOTIFY"){
}
}
function onOpen(event) {}
function one rror() {}
function onClose() {}
标签:Java,springboot,Websocket,userId,server,import,websocket,type,public
来源: https://blog.csdn.net/sky_eyeland/article/details/98969660