WebSocket

1.使用

  • 前端js
function createScoket(token){
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        var host = window.location.origin.replace("http:","ws:")
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket(host+":9000/ws/"+token);
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            socket.send("这是来自客户端的消息" + location.href + new Date());
        };

        //获得消息事件
        socket.onmessage = function(result) {
            console.log(result)
            var data = $.parseJSON(result.data);
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("Socket发生了错误");
        }
        //窗口关闭
        $(window).unload(function(event){
            socket.close();
        });
    }
    return socket;
}

var socket = createScoket(token); 
  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • WSServer
@ServerEndpoint("/ws/{token}")
@Component
public class OrderWSServer {
    public static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token){
        System.out.println("浏览器和服务器建立连接:"+token);
        //建立和浏览器的会话的映射关系
        clients.put(token,session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    @OnClose
    public void onClose(@PathParam("token") String token){
        System.out.println("浏览器和服务器断开连接:"+token);
        clients.remove(token);
    }

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

//    // 此为广播消息
//    public void sendAllMessage(String message) {
//        log.info("【websocket消息】广播消息:"+message);
//        for(WebSocket webSocket : webSockets) {
//            try {
//                if(webSocket.session.isOpen()) {
//                    webSocket.session.getAsyncRemote().sendText(message);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    // 此为单点消息
//    public void sendOneMessage(String userId, String message) {
//        Session session = sessionPool.get(userId);
//        if (session != null&&session.isOpen()) {
//            try {
//                log.info("【websocket消息】 单点消息:"+message);
//                session.getAsyncRemote().sendText(message);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    // 此为单点消息(多人)
//    public void sendMoreMessage(String[] userIds, String message) {
//        for(String userId:userIds) {
//            Session session = sessionPool.get(userId);
//            if (session != null&&session.isOpen()) {
//                try {
//                    log.info("【websocket消息】 单点消息:"+message);
//                    session.getAsyncRemote().sendText(message);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

}
  • 调用WSServe
@Configuration
public class ReceiveHandler {

    @RabbitListener(queues = {RabbitmqConfig.ORDER_RESULT_TOPIC})
    public void receive_order(OrderMQResult orderMQResult){
//        System.out.println("消费消息:"+JSON.toJSONString(orderMQResult));
        //找到客户端
        Session session = null;
        int count = 3;
        //超时重连
        while(count-- > 0){
            session = OrderWSServer.clients.get(orderMQResult.getToken());
            if(session!=null){
                //说明已经拿到了,发送消息
                try {
                    //消息需要是Json格式的
//                    session.getBasicRemote().sendText(orderMQResult.toString());
                    session.getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
posted @ 2023-08-05 13:45  lwx_R  阅读(13)  评论(0编辑  收藏  举报