websocket 在web項目中的应用(服务器推消息)

本文介绍了在Web项目中使用WebSocket进行服务器到客户端的消息推送。客户端通过创建WebSocket连接,并设置打开、关闭、错误和接收到消息时的回调函数。服务端使用`@ServerEndpoint`注解定义端点,并在`onOpen`、`onMessage`、`onClose`和`onError`方法中处理相关逻辑,实现广播消息功能。
摘要由CSDN通过智能技术生成

客户端代码:

var socket = null;
var url = "wss://" + window.location.host + "/projectName/ws";
if(window.location.protocol == "http:") {
    url = "ws://" + window.location.host + "/projectName/ws";
}
var timeout;
var reconnecting = false;//是否在重连

//重新连接
function reConnectWebsocket() {
    if(reconnecting) {
        return;
    };
    reconnecting = true;
    //有定时任务 先取消再设置
    timeout && clearTimeout(timeout);
    //10秒重连
    timeout = setTimeout(function () {
        console.log('try to reconnect websocket');
        reconnecting = false;
        createWebsocket();
    }, 10000);

}
//初始化websocket
function createWebsocket() {
    try {
        if ("WebSocket" in window) {
            socket = new WebSocket(url);
        } else if ("MozWebSocket" in window) {
            socket = new MozWebSocket(url);
        } else {
            socket = new WebSocket(url);
        }
        socket.onopen = function () {
            console.log("connect to websocket");
        };
        socket.onmessage = function (evt) {
            console.log('recv message:'+ evt.data);
            WsServiceListReload(selectedGroupName);
        };
        socket.onclose = function (evt) {
            console.log(evt);
            reConnectWebsocket();
        }
        socket.onerror = function (evt) {
            console.log(evt);
        }
    } catch (err) {
        console.error(err);
        reConnectWebsocket();
    }

}
createWebsocket();

服务端:

import org.apache.log4j.Logger

import javax.websocket.CloseReason
import javax.websocket.OnClose
import javax.websocket.OnError
import javax.websocket.OnMessage
import javax.websocket.OnOpen
import javax.websocket.Session
import javax.websocket.server.ServerEndpoint
import java.util.concurrent.ConcurrentHashMap


@ServerEndpoint("/ws")  //websocket连接地址
class OriginWebSocketService {

    private final Logger log = Logger.getLogger(this.class);//日志
    //存储客户端session
    public static Map<String, Session> conMap = new ConcurrentHashMap<String, Session>();
    OriginWebSocketService() {
        System.out.println("OriginWebSocketService()");
    }

    @OnOpen
    public void onOpen(Session session) throws IOException {
        //session.getBasicRemote().sendText("你好,客户端");
        log.info("client connect ,client id:" << session.getId());
        conMap.put(session.getId(),session);


    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("收到消息:" + message);
    }


    @OnError
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        log.info("client disconnect ,client id:" << session.getId());
        log.warn(reason.toString());
        conMap.remove(session.getId());
    }

    //广播消息
    public static broadcast(String json)   {
        try{
            for(String key:conMap.keySet())  {
                Session val = conMap.get(key);
                if(val != null) {
                    val.getBasicRemote().sendText(json);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值