Java WebSocket实现前后端消息推送

WebSocket的代码编写会根据业务逻辑而进行变化,需要去理解编写思路,这样才能在工作中使用得游刃有余。

1. 引入依赖

<!-- websocket -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.  编写WebSocketConfig配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter getServerEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

3. 编写WebSocket服务类

下面的服务类中,可以编写多个sendMeg方法(写法比较多样化),作用是发送消息回前端,使用方式就是你在自己的业务代码中自行调用,例(serviceImpl中调用):

WebSocketServer.sendCountToUaa(ownerId, unreadNewsCount);
import com.sms.service.InternalNewsService;
import com.sms.service.impl.InternalNewsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Websocket服务,推送信息
 */

@Slf4j
@Component
@ServerEndpoint("/webSocket/sms")
public class WebSocketServer {

    /**
     * 定义集合,用于存储连接信息
     * 根据业务需求自定义,数据格式可随意变化
     */
    //浏览器端连接,这种数据格式是因为考虑到同一个用户账号可以在不同的浏览器登录,所以一个用户需要保存多个连接
    private static final ConcurrentHashMap<String, ArrayList<Session>> sessionMap = new ConcurrentHashMap<>();
    //微信端连接
    private static final List<Session> wxSessionList = new ArrayList<>();

    /**
     * 作用:
     * 这里使用@Autowared是无法正常注入对象的,需要注入外部对象就需要使用这种方式
     * 需在启动类也就是main方法中加入:WebSocketServer.setApplicationContext(context);
     * context参数是启动类中run方法的返回值
     * 使用:
     * 在需要对象的地方使用
     * 例:
     * UserServiceImpl userServiceImpl = applicationContext.getBean(UserService.class);
     */
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 前端关闭页面或者主动关闭websocket链接,都会执行@OnClose
     */
    @OnClose
    public void close(Session session) {
        if (null == session) {
            return;
        }
        /**
         * 以下代码都是根据业务逻辑编写,写法并不固定
         */
        //关闭微信端中的session
        ListIterator<Session> sessionListIterator = wxSessionList.listIterator();
        while (sessionListIterator.hasNext()) {
            Session next = sessionListIterator.next();
            if (session == next) {
                sessionListIterator.remove();
                return;
            }
        }
        //关闭浏览器端中的session
        Iterator<Map.Entry<String, ArrayList<Session>>> iterator = sessionMap.entrySet().iterator();
        while (iterator.hasNext()) {
            ArrayList<Session> values = iterator.next().getValue();
            if (null == values || 1 > values.size()) {
                continue;
            }
            for (int i = 0; i < values.size(); i++) {
                Session sess = values.get(i);
                if (null == sess) {
                    continue;
                }
                if (session == sess) {
                    values.remove(i--);
                    return;
                }
            }
        }
    }

    /**
     * 前端连接后端socket时执行@OnMessage,前后端建立起连接,后端保存连接
     */
    @OnMessage
    public void onMessage(String userId, Session session) {
        if (StringUtils.isEmpty(userId) || null == session) {
            return;
        }
        if ("ykj".equals(userId)) {
            //微信端消息标识,自定义,没有微信端可直接将这个if删掉
            wxSessionList.add(session);
        } else {
            //接收到消息后,找到对应的session
            ArrayList<Session> sessions = sessionMap.get(userId);
            if (null == sessions) {
                sessions = new ArrayList<>();
            } else {
                //遍历,看该session是否存在,如果存在代表是在心跳检测操作
                for (int i = 0; i < sessions.size(); i++) {
                    if (sessions.get(i) == session) {
                        try {
                            //发送消息回前端
                            session.getAsyncRemote().sendText("{\"heartbeat\":\"socket心跳检测成功!!!\"}");
                            return;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            //说明session不存在,添加到列表
            sessions.add(session);
            sessionMap.put(userId, sessions);

            //查询当前用户未读消息条数(业务代码,查询数据库)
            InternalNewsService internalNewsService = applicationContext.getBean(InternalNewsService.class);
            Integer newsCount = internalNewsService.selectUnreadNewsCount(userId, 0, 4);

            if (newsCount == null) {
                session.getAsyncRemote().sendText("0");//发送消息回前端
            } else {
                session.getAsyncRemote().sendText(newsCount.toString());//发送消息回前端
            }
            return;
        }
        try {
            session.getAsyncRemote().sendText("200");//发送消息回前端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送数据到前端
     *
     * @param msg
     */
    public static void sendMsg(String userIds, String msg) {
        if (StringUtils.isEmpty(userIds) || StringUtils.isEmpty(msg)) {
            return;
        }
        String[] user_id = userIds.split(",");
        int uis = user_id.length;
        if (1 > uis) {
            return;
        }
        for (int ii = 0; ii < uis; ii++) {
            String userId = user_id[ii];
            if (StringUtils.isEmpty(userId)) {
                continue;
            }
            ArrayList<Session> sessions = sessionMap.get(userId);
            if (null == sessions || 1 > sessions.size()) {
                continue;
            }
            Iterator<Session> iterator = sessions.iterator();
            while (iterator.hasNext()) {
                Session next = iterator.next();
                if (null == next || !next.isOpen()) {
                    continue;
                }
                try {
                    next.getBasicRemote().sendText(msg);
                    //System.out.println("推送给socket:" + next);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 发送数据到前端uaa端
     */
    public static void sendCountToUaa(String userId, Integer count) {
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        ArrayList<Session> sessions = sessionMap.get(userId);
        if (null == sessions || 1 > sessions.size()) {
            return;
        }
        Iterator<Session> iterator = sessions.iterator();
        while (iterator.hasNext()) {
            Session next = iterator.next();
            if (null == next || !next.isOpen()) {
                continue;
            }
            try {
                //next.getBasicRemote().sendText(count.toString());
                next.getAsyncRemote().sendText(count.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给微信端用户推送消息
     *
     * @param msg
     */
    public static void sendToVXMsg(String msg) {
        ListIterator<Session> sessionListIterator = wxSessionList.listIterator();
        while (sessionListIterator.hasNext()) {
            Session session = sessionListIterator.next();
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
要使用Undertow实现WebSocket前后端消息推送,可以按照以下步骤进行: 1. 在后端实现WebSocket处理器,代码如下: ```java import io.undertow.server.HttpServerExchange; import io.undertow.websockets.core.*; import io.undertow.websockets.spi.WebSocketHttpExchange; import io.undertow.websockets.spi.WebSocketSession; public class WebSocketHandler implements WebSocketConnectionCallback { @Override public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) { // WebSocket连接建立时触发 System.out.println("WebSocket连接建立"); // 创建WebSocket会话 WebSocketSession session = new UndertowWebSocketSession(channel); // 将WebSocket会话保存到会话管理器中 WebSocketSessionManager.addSession(session); // 注册WebSocket消息处理器 channel.getReceiveSetter().set(new WebSocketMessageHandler(session)); channel.resumeReceives(); } } class WebSocketMessageHandler implements WebSocketCallback<WebSocketChannel> { private WebSocketSession session; public WebSocketMessageHandler(WebSocketSession session) { this.session = session; } @Override public void onError(WebSocketChannel channel, Throwable throwable) { // WebSocket出错时触发 System.out.println("WebSocket出错"); throwable.printStackTrace(); } @Override public void onClose(WebSocketChannel channel, StreamSourceFrameChannel channel1) throws IOException { // WebSocket连接关闭时触发 System.out.println("WebSocket连接关闭"); // 从会话管理器中删除WebSocket会话 WebSocketSessionManager.removeSession(session); } @Override public void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { // 收到完整的文本消息时触发 System.out.println("收到文本消息:" + message.getData()); // 处理WebSocket消息 // ... } } ``` 2. 在Undertow服务器中添加WebSocket处理器,代码如下: ```java import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.RoutingHandler; import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.server.handlers.resource.ResourceHandler; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.server.handlers.websocket.WebSocketProtocolHandshakeHandler; public class WebSocketServer { public static void main(String[] args) { // 创建Web资源管理器 ResourceManager resourceManager = new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), "web"); // 创建Web资源处理器 ResourceHandler resourceHandler = new ResourceHandler(resourceManager); // 创建WebSocket处理器 WebSocketConnectionCallback callback = new WebSocketHandler(); WebSocketProtocolHandshakeHandler websocketHandler = new WebSocketProtocolHandshakeHandler(callback); // 创建路由处理器 RoutingHandler routingHandler = Handlers.routing() .get("/", resourceHandler) .get("/{path}", resourceHandler) .get("/websocket", websocketHandler); // 创建路径处理器 PathHandler pathHandler = Handlers.path(routingHandler) .addPrefixPath("/", resourceHandler); // 创建Undertow服务器 Undertow server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(pathHandler) .build(); // 启动Undertow服务器 server.start(); } } ``` 3. 在前端使用WebSocket连接到后端,代码如下: ```javascript var websocket = new WebSocket("ws://localhost:8080/websocket"); websocket.onopen = function() { console.log("WebSocket连接建立"); }; websocket.onclose = function() { console.log("WebSocket连接关闭"); }; websocket.onerror = function() { console.log("WebSocket出错"); }; websocket.onmessage = function(event) { console.log("收到文本消息:" + event.data); }; ``` 4. 在后端向前端发送消息,代码如下: ```java import io.undertow.websockets.core.*; import io.undertow.websockets.spi.WebSocketSession; public class WebSocketSessionManager { private static Set<WebSocketSession> sessions = new HashSet<>(); public static void addSession(WebSocketSession session) { sessions.add(session); } public static void removeSession(WebSocketSession session) { sessions.remove(session); } public static void sendMessage(String message) { for (WebSocketSession session : sessions) { try { session.send(new StringWebSocketMessage(message)); } catch (IOException e) { e.printStackTrace(); } } } } ``` 调用`WebSocketSessionManager.sendMessage()`方法即可向所有前端客户端发送消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值