websocket实现服务器端消息推送

5 篇文章 0 订阅
5 篇文章 0 订阅

因为工作原因,需要实现一个服务器端消息推送的功能,就类似发布一篇文章,同时推送给指定用户,最后决定采用websocket的方式实现该功能。

一、准备

实现主要分为服务器端和客户端,客户端通过websocket与服务器端保持连接,这样服务器就可以向客户端主动发起请求。

二、服务器端

服务器端我是使用的springboot,要是用websocket只需要引入websocket的依赖即可

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<version>2.0.4.RELEASE</version>
</dependency>

然后主要需要实现两个类,一个是websocket的配置类,还有一个是提供其他服务调用的Service

WebSocketConfig.java

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

/**
 * @author chenwenrui
 * @description: WebSocket配置类
 * @date 2019/6/11 18:17
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

这个配置文件只起到一个作用就是注册ServerEndpointExporter对象,这个bean会自动注册使用了@ServerEndpoint注解声明的类,比如下面的WebSocketService类

WebSocketService.java

import org.springframework.stereotype.Service;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * @author chenwenrui
 * @description: TODO
 * @date 2019/6/11 18:11
 */
@Service
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketService {

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketSet对象。
     */
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 客户端用户id
     */
    private String userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (userId != null) {
            webSocketSet.add(this);     //加入set中
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     *
     * @param message 消息内容
     * @param userIds 需要发送的客户端用户id列表
     */
    public void sendMessage(String message, List<String> userIds) {
        // 需要发送消息的客户端
        List<WebSocketService> services = webSocketSet.stream()
                .filter(temp -> userIds.contains(temp.userId))
                .collect(Collectors.toList());
        services.forEach(temp -> {
            try {
                temp.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}

@ServerEndpoint表示这是一个websocket,因为登录的每一个用户都是一个客户端,所以这里使用用户的id区分不同的客户端,以方便给对应的用户发送消息,每一个客户端发起websocket连接请求的时候,需要把对应对象(WebSocketService,主要是保存userId以及对应客户端的Session)保存到集合里(要供其他服务调用),用户关闭连接的时候同时需要从集合中去除。

三、客户端

客户端我是使用的vue,只需要在mounted()钩子里面打开websocket的连接即可

mounted(){
	let websocket = new WebSocket(
		"ws://localhost:8089/websocket/" + userId
	);
	 //连接成功建立的回调方法
	websocket.onopen = function(event) {
		console.log("连接成功");
	};
	//接收到消息的回调方法
	websocket.onmessage = function(event) {
		console.log(event);
	};
	 //连接关闭的回调方法
	websocket.onclose = function() {
		console.log("连接关闭");
	};
	//连接发生错误的回调方法
	websocket.onerror = function() {
		console.log("发生错误");
	};
}

在实例化WebSocket对象的时候,添加了当前登录用户的用户id(token也行,只要是能确保当前状态下是唯一的),用于标记每一个客户端对应的WebSocket连接。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用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()`方法即可向所有前客户消息
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值