一个html页面,多个子页面,创建一个还是多个websocket? 15
前端只有一个html主页面,其他子页面通过按钮点击进行跳转,这种场景是创建一个websocket实现所有服务,还是多个websocket实现不同服务好?还是不同的跳转页面...
前端只有一个html主页面,其他子页面通过按钮点击进行跳转,这种场景是创建一个websocket实现所有服务,还是多个websocket实现不同服务好?
还是不同的跳转页面,使用不同的websocket连接?页面跳转后,关闭之前的连接,建立新的连接? 展开
还是不同的跳转页面,使用不同的websocket连接?页面跳转后,关闭之前的连接,建立新的连接? 展开
2个回答
展开全部
多个长连接
使用 用户-设备-连接 存放后台的session
private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>> users; // 用户账号 - 设备 - 连接
每次给某个用户的PC-WEB设备的所有连接进行发送通知,所有页面都可以同时收到
package com.base.sbc.config.webscoket;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import com.base.sbc.config.utils.JsonUtils;
import com.base.sbc.config.utils.SpringContextHolder;
import com.base.sbc.message.entity.Message;
import com.base.sbc.message.service.MessageService;
import io.jsonwebtoken.Claims;
@ServerEndpoint(value = "/websocket/{chat_token}")
@Component
public class WebSocketServer {
// @Autowired //注入不了
// private MessageService messageService;
// private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>> users; // 用户账号 - 设备 - 连接
static {
users = new ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>>();
}
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
*
* @throws IOException
*/
@OnOpen
public void onOpen(Session session, @PathParam("chat_token") String chat_token) throws IOException {
String userid = "";
String cookie = "";
Boolean notice = false;
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
notice = true;
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
this.session = session;
// 判断用户是否存在没有则新增
ConcurrentHashMap<String, WebSocketServer> user = users.get(userid);
if (user == null || user.isEmpty()) {
user = new ConcurrentHashMap<String, WebSocketServer>();
user.put(cookie, this);
users.put(userid, user);
} else {
WebSocketServer cookieSession = user.get(cookie);
if (cookieSession == null) {
user.put(cookie, this);
}
users.put(userid, user);
}
if (notice) {
// 刷新 场景:右上角消息栏的刷新 清空,已读 消息或通知后,或者重新连接
MessageService messageService = SpringContextHolder.getBean(MessageService.class);
List<Message> list = messageService.getUserNotice(userid);
if (list != null && list.size() > 0) {
sendMessageToUser(userid, JsonUtils.beanToJson(list));
}
}
// 集群方式 本数量统计不正确 没有意义
// int i = 0;
// if (users != null) {
// for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
// String key = iterator.next();// 获取所有的用户登录账号
// ConcurrentHashMap<String, WebSocketServer> userNames = users.get(key);
// if (userNames != null && !userNames.isEmpty()) {
// i++;
// }
// }
// }
// sendMessageToUsers("userNum:" + i);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("chat_token") String chat_token) {
String userid = "";
String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
ConcurrentHashMap<String, WebSocketServer> userids = users.get(userid);
if (userids != null) {
userids.remove(cookie);
}
// 可以将现有的记录推送给展示的页面
}
public final String HEARTCHECK = "heartCheck";
public final String REFRESHMESSAGE = "refreshMessage";
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @throws IOException
*/
@OnMessage
public void onMessage(String message, WebSocketServer session, @PathParam("chat_token") String chat_token)
throws IOException {
String userid = "";
// String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
// cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
// cookie = chat_token;
}
if (HEARTCHECK.equals(message)) {
sendMessage(message);
} else if (REFRESHMESSAGE.equals(message)) {
// 刷新 场景:右上角消息栏的刷新 清空,已读 消息或通知后,或者重新连接
MessageService messageService = SpringContextHolder.getBean(MessageService.class);
List<Message> list = messageService.getUserNotice(userid);
if (list != null && list.size() > 0) {
sendMessageToUser(userid, JsonUtils.beanToJson(list));
} else {
sendMessageToUser(userid, "[]");
}
}
// sendMessageToUsers(message);
}
/**
* 连接错误
*
* @param session
* @param exception
* @param chat_token
* @throws IOException
*/
@OnError
public void onError(Session session, Throwable exception, @PathParam("chat_token") String chat_token)
throws IOException {
String userid = "";
String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
if (session.isOpen()) {
session.close();
}
// 获取用户 设备
ConcurrentHashMap<String, WebSocketServer> userids = users.get(userid);
if (userids != null) {
userids.remove(cookie);
}
// 可以将现有的记录推送给展示的页面
}
/**
* 给当前用户发送信息
*
* @param msg
* @throws IOException
*/
public void sendMessage(String msg) throws IOException {
this.session.getBasicRemote().sendText(msg);
}
/**
* 给用户发送信息
*
* @param userid 用户名称
* @param msg 消息
* @throws IOException
*/
public static int sendMessageToUser(String userid, String msg) {
int i = 0;
for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();// 获取所有的用户登录账号
if (key.equals(userid)) {
ConcurrentHashMap<String, WebSocketServer> userids = users.get(key);
for (Iterator<String> cookies = userids.keySet().iterator(); cookies.hasNext();) {
String cookie = cookies.next();
WebSocketServer user = userids.get(cookie);
try {
user.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
i += 1;
}
}
return i;
}
/**
* 给所有用户发送信息
*
* @param userid 用户名称
* @param msg 消息
* @throws IOException
*/
public static void sendMessageToUsers(String msg) {
for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();// 获取所有的用户登录账号
ConcurrentHashMap<String, WebSocketServer> userids = users.get(key);
for (Iterator<String> cookies = userids.keySet().iterator(); cookies.hasNext();) {
String cookie = cookies.next();
WebSocketServer user = userids.get(cookie);
try {
user.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
使用 用户-设备-连接 存放后台的session
private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>> users; // 用户账号 - 设备 - 连接
每次给某个用户的PC-WEB设备的所有连接进行发送通知,所有页面都可以同时收到
package com.base.sbc.config.webscoket;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import com.base.sbc.config.utils.JsonUtils;
import com.base.sbc.config.utils.SpringContextHolder;
import com.base.sbc.message.entity.Message;
import com.base.sbc.message.service.MessageService;
import io.jsonwebtoken.Claims;
@ServerEndpoint(value = "/websocket/{chat_token}")
@Component
public class WebSocketServer {
// @Autowired //注入不了
// private MessageService messageService;
// private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>> users; // 用户账号 - 设备 - 连接
static {
users = new ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketServer>>();
}
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
*
* @throws IOException
*/
@OnOpen
public void onOpen(Session session, @PathParam("chat_token") String chat_token) throws IOException {
String userid = "";
String cookie = "";
Boolean notice = false;
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
notice = true;
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
this.session = session;
// 判断用户是否存在没有则新增
ConcurrentHashMap<String, WebSocketServer> user = users.get(userid);
if (user == null || user.isEmpty()) {
user = new ConcurrentHashMap<String, WebSocketServer>();
user.put(cookie, this);
users.put(userid, user);
} else {
WebSocketServer cookieSession = user.get(cookie);
if (cookieSession == null) {
user.put(cookie, this);
}
users.put(userid, user);
}
if (notice) {
// 刷新 场景:右上角消息栏的刷新 清空,已读 消息或通知后,或者重新连接
MessageService messageService = SpringContextHolder.getBean(MessageService.class);
List<Message> list = messageService.getUserNotice(userid);
if (list != null && list.size() > 0) {
sendMessageToUser(userid, JsonUtils.beanToJson(list));
}
}
// 集群方式 本数量统计不正确 没有意义
// int i = 0;
// if (users != null) {
// for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
// String key = iterator.next();// 获取所有的用户登录账号
// ConcurrentHashMap<String, WebSocketServer> userNames = users.get(key);
// if (userNames != null && !userNames.isEmpty()) {
// i++;
// }
// }
// }
// sendMessageToUsers("userNum:" + i);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("chat_token") String chat_token) {
String userid = "";
String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
ConcurrentHashMap<String, WebSocketServer> userids = users.get(userid);
if (userids != null) {
userids.remove(cookie);
}
// 可以将现有的记录推送给展示的页面
}
public final String HEARTCHECK = "heartCheck";
public final String REFRESHMESSAGE = "refreshMessage";
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @throws IOException
*/
@OnMessage
public void onMessage(String message, WebSocketServer session, @PathParam("chat_token") String chat_token)
throws IOException {
String userid = "";
// String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
// cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
// cookie = chat_token;
}
if (HEARTCHECK.equals(message)) {
sendMessage(message);
} else if (REFRESHMESSAGE.equals(message)) {
// 刷新 场景:右上角消息栏的刷新 清空,已读 消息或通知后,或者重新连接
MessageService messageService = SpringContextHolder.getBean(MessageService.class);
List<Message> list = messageService.getUserNotice(userid);
if (list != null && list.size() > 0) {
sendMessageToUser(userid, JsonUtils.beanToJson(list));
} else {
sendMessageToUser(userid, "[]");
}
}
// sendMessageToUsers(message);
}
/**
* 连接错误
*
* @param session
* @param exception
* @param chat_token
* @throws IOException
*/
@OnError
public void onError(Session session, Throwable exception, @PathParam("chat_token") String chat_token)
throws IOException {
String userid = "";
String cookie = "";
try {
Claims jwt = TokenUtils.parseJWT(chat_token);
userid = jwt.getSubject();
cookie = jwt.getAudience();
} catch (Exception e) {
userid = "temp" + chat_token;
cookie = chat_token;
}
if (session.isOpen()) {
session.close();
}
// 获取用户 设备
ConcurrentHashMap<String, WebSocketServer> userids = users.get(userid);
if (userids != null) {
userids.remove(cookie);
}
// 可以将现有的记录推送给展示的页面
}
/**
* 给当前用户发送信息
*
* @param msg
* @throws IOException
*/
public void sendMessage(String msg) throws IOException {
this.session.getBasicRemote().sendText(msg);
}
/**
* 给用户发送信息
*
* @param userid 用户名称
* @param msg 消息
* @throws IOException
*/
public static int sendMessageToUser(String userid, String msg) {
int i = 0;
for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();// 获取所有的用户登录账号
if (key.equals(userid)) {
ConcurrentHashMap<String, WebSocketServer> userids = users.get(key);
for (Iterator<String> cookies = userids.keySet().iterator(); cookies.hasNext();) {
String cookie = cookies.next();
WebSocketServer user = userids.get(cookie);
try {
user.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
i += 1;
}
}
return i;
}
/**
* 给所有用户发送信息
*
* @param userid 用户名称
* @param msg 消息
* @throws IOException
*/
public static void sendMessageToUsers(String msg) {
for (Iterator<String> iterator = users.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();// 获取所有的用户登录账号
ConcurrentHashMap<String, WebSocketServer> userids = users.get(key);
for (Iterator<String> cookies = userids.keySet().iterator(); cookies.hasNext();) {
String cookie = cookies.next();
WebSocketServer user = userids.get(cookie);
try {
user.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询