websocket实现单发,群发

package com.yzd.server.websocket;

import com.yzd.server.dao.mapper.EventMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: liury
 * @Description: webSocket
 * @DateTime: 2022/6/19 20:54
 **/
@Slf4j
@Component
@ServerEndpoint("/webSocket/{id}")
public class WebSocket {
    private static int onlineCount = 0;

    @Resource
    private EventMapper eventMapper;
    // 这里用ConcurrentHashMap 因为他是一个线程安全的Map
    private static ConcurrentHashMap<Long, WebSocket> websockets = new ConcurrentHashMap<>();

    private Session session;


    @OnOpen
    public void onOpen(@PathParam("id") Long id, Session session) {  // 接收到前端传来的用户ID
        this.session = session;
        websockets.put(id, this);  //将ID作为key,当前的对象作为Value
        log.info("【建立连接】 用户为:" + this.session);
        log.info("【建立连接】 用户Id为:" + id);
        log.info("【建立连接】 总数为:" + websockets.size());
    }


    /**
     * 有用户连接断开时候触发该方法
     */
    @OnClose
    public void onClose() {
        websockets.remove(this); // 将当前的对象从集合中删除
        log.info("【连接断开】 用户为:" + this.session);
        log.info("【连接断开】 总数为:" + websockets.size());
    }


    @OnMessage

    public void onMessage(String message) throws IOException {
        if ("ping".equals(message)) {
            log.info("--------------------------webSocket心跳检测:" + message);
        } else {
            log.info("【收到客户端发的消息】:" + message);
        }


    }


    @OnError

    public void onError(Session session, Throwable error) {
        error.printStackTrace();

    }


    public static void sendMessageAll(String message) throws IOException {

//        if (sessions.size() != 0) {
//            for (Session s : sessions) {
//                if (s != null) {
//                    s.getAsyncRemote().sendText(message);
//                }
//            }
//        }


    }


    /**
     * 发送消息方法  【为了方便大家理解,我这里直接不封装了】
     *
     * @param message 消息
     * @param userId  用户ID
     */

    public void sendMessage(String message, Long userId) {
        if (userId == null) {  // 如果等于null则证明是群发
            // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来
            Iterator<Map.Entry<Long, WebSocket>> iterator = websockets.entrySet().iterator();
            List<Long> userIds = eventMapper.selectUserId();
            // 这个就是遍历这个集合的过程....
            while (iterator.hasNext()) {
                // 获取每一个Entry实例
                Map.Entry<Long, WebSocket> entry = iterator.next();
                // 获取每一个Value,而这个Value就是WebSocket的实例
                WebSocket webSocket = entry.getValue();
                // 获取每一个Key,这个Key就是用户ID
                Long key = entry.getKey();
                // 接下来就是遍历群发

                for (Long id : userIds) {
                    if (id.equals(key)) {
                        try {
                            if (webSocket.session.isOpen()) {
                                log.info("广播消息 【给用户】 :" + webSocket + "发送消息" + "【" + message + "】");
                                webSocket.session.getBasicRemote().sendText(message); // 发送!!!!!!!!!
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        } else {  // 如果不是群发,则判断ID,其余步骤一致
            // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来
            Iterator<Map.Entry<Long, WebSocket>> iterator2 = websockets.entrySet().iterator();
            // 这个就是遍历这个集合的过程....
            while (iterator2.hasNext()) {
                // 获取每一个Entry实例
                Map.Entry<Long, WebSocket> entry = iterator2.next();
                // 获取每一个Value,而这个Value就是WebSocket的实例
                WebSocket webSocket = entry.getValue();
                // 获取每一个Key,这个Key就是用户ID
                Long key = entry.getKey();
                // 判断用户ID与当前的Key相等
                if (userId.equals(key)) {

                    try {
                        if (webSocket.session.isOpen()) {
                            log.info("广播消息 【给用户】 :" + key + "发送消息" + "【" + message + "】"); // 打印
                            webSocket.session.getBasicRemote().sendText(message);  // 则发送给当前的用户即可
                        }

                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }
    }


    public static synchronized void addOnlineCount() {

        WebSocket.onlineCount++;

    }


    public static synchronized void subOnlineCount() {

        WebSocket.onlineCount--;

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用SpringBoot实现单发群发消息的WebSocket示例代码: 1. 首先,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类,用于注册WebSocket处理程序: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyWebSocketHandler(), "/websocket") .addInterceptors(new HttpSessionHandshakeInterceptor()); } } ``` 3. 创建WebSocket处理程序,实现单发群发消息的逻辑: ```java public class MyWebSocketHandler extends TextWebSocketHandler { private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.put(session.getId(), session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session.getId()); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); JSONObject jsonObject = JSONObject.parseObject(payload); String type = jsonObject.getString("type"); String content = jsonObject.getString("content"); if ("single".equals(type)) { String to = jsonObject.getString("to"); WebSocketSession toSession = sessions.get(to); if (toSession != null && toSession.isOpen()) { toSession.sendMessage(new TextMessage(content)); } } else if ("group".equals(type)) { for (WebSocketSession s : sessions.values()) { if (s.isOpen()) { s.sendMessage(new TextMessage(content)); } } } } } ``` 4. 在控制器中注入WebSocket处理程序,并提供单发群发消息的接口: ```java @RestController public class WebSocketController { @Autowired private MyWebSocketHandler webSocketHandler; @PostMapping("/send/single") public void sendSingleMessage(@RequestParam String to, @RequestParam String message) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "single"); jsonObject.put("to", to); jsonObject.put("content", message); TextMessage textMessage = new TextMessage(jsonObject.toJSONString()); for (WebSocketSession session : webSocketHandler.sessions.values()) { if (session.isOpen()) { session.sendMessage(textMessage); } } } @PostMapping("/send/group") public void sendGroupMessage(@RequestParam String message) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "group"); jsonObject.put("content", message); TextMessage textMessage = new TextMessage(jsonObject.toJSONString()); for (WebSocketSession session : webSocketHandler.sessions.values()) { if (session.isOpen()) { session.sendMessage(textMessage); } } } } ``` 以上代码实现了一个简单的SpringBoot WebSocket应用程序,可以通过发送POST请求来发送单发群发消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值