实现长连接
由于websocket连接成功过段时间自动关闭,无法继续获取消息
于是我就想到一个办法,就是自动关闭时再重新创建一次(因为自动关闭也不是很快就关闭的,所以我就这么写),虽然实现方式不是很好,但是也暂时的实现了长连接方式
前端JS
var websocket = null;
var host = document.location.host;
var username = "1001"; // 获得当前登录人员的userName --这里使用当前项目ID做判断
var judgeTemp = 0;
// alert(username)
createWebSorket();
function createWebSorket(){
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window) {
websocket = new WebSocket('ws://' + host + '/Project/webSocket/' + username);
initEventHandle();
} else {
alert('当前浏览器 Not support websocket,消息推送将无法使用')
}
}
function initEventHandle(){
//连接发生错误的回调方法
websocket.onerror = function() {
judgeTemp = 1;
//这里就是你要显示的信息的函数(自定义)
setMessageInnerHTML("WebSocket消息推送连接发生错误",1);
};
//连接成功建立的回调方法
websocket.onopen = function() {
//这里就是你要显示的信息的函数(自定义)
setMessageInnerHTML("WebSocket消息推送连接成功",1);
console.log("成功连接---"+judgeTemp)
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
//这里就是你要显示的信息的函数(自定义)
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
console.log("关闭连接---"+judgeTemp)
if(judgeTemp == 1){
//这里就是你要显示的信息的函数(自定义)
setMessageInnerHTML("WebSocket消息推送连接关闭",1);
}else{
createWebSorket();
}
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
judgeTemp = 1;
closeWebSocket();
}
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
后端实现
我这里是用SSH的框架(其实也没啥区别的)
package com.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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 net.sf.json.JSONObject;
@ServerEndpoint("/webSocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
// private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private static List<Map<String, WebSocket>> clients = null;
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
//为了实现多个页面登录同一个账号时,同时推送全部页面
if(clients == null) {
synchronized (WebSocket.class) {
if(clients == null) {
clients = new ArrayList<Map<String, WebSocket>>();
}
}
}
addOnlineCount();
Map<String, WebSocket> clien = new ConcurrentHashMap<String, WebSocket>();
clien.put(username, this);
clients.add(clien);
//clients.put(username, this);
//System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
for(int i=0; i< clients.size(); i++) {
Map<String, WebSocket> clien = clients.get(i);
for (WebSocket item : clien.values()) {
if(item.session.equals(session))
clients.remove(i);
}
}
//clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
String mes = (String) jsonTo.get("message");
if (!jsonTo.get("To").equals("All")){
sendMessageTo(mes, jsonTo.get("To").toString());
}else{
sendMessageAll(mes);
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
/*for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
} */
for(int i=0; i< clients.size(); i++) {
Map<String, WebSocket> clien = clients.get(i);
for (WebSocket item : clien.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
}
public void sendMessageAll(String message) throws IOException {
/* for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
} */
for(int i=0; i< clients.size(); i++) {
Map<String, WebSocket> clien = clients.get(i);
for (WebSocket item : clien.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
/*public static synchronized Map<String, WebSocket> getClients() {
return clients;
} */
public static synchronized List<Map<String, WebSocket>> getClients() {
return clients;
}
}
备注
如果遇到无法找到问题
通道:https://blog.csdn.net/weixin_43992507/article/details/103256233
或
nginx下无法连接websocket
通道:https://blog.csdn.net/weixin_43992507/article/details/103337106