websocket定时推送

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

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

@Configuration
public class WebSocketConfig {
    /**
     * 	注入ServerEndpointExporter,
     * 	这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}



import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
@ServerEndpoint("/websocket/{userId}")  // 接口路径 ws://localhost:8087/webSocket/userId;
public class WebSocket {
    private static AsynSendMsg asyncSendMsg;

    @Autowired
    public void setAsynSendMsg(AsynSendMsg asyncSendMsg) {
        WebSocket.asyncSendMsg = asyncSendMsg;
    }

    public Logger log = LogManager.getLogger(getClass());

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

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    //虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
    //  注:底下WebSocket是当前类名
    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    // 用来存在线连接用户信息
    private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();


    public Session getSession() {
        return session;
    }

    public String getUserId() {
        return userId;
    }

    public static CopyOnWriteArraySet<WebSocket> getWebSockets() {
        return webSockets;
    }

    public static ConcurrentHashMap<String, Session> getSessionPool() {
        return sessionPool;
    }

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        try {
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
        } catch (Exception e) {
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            log.info("【websocket消息】连接断开,总数为:"+webSockets.size());
        } catch (Exception e) {
        }
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) throws InterruptedException {
        log.info("【websocket消息】收到客户端消息:"+message);
        asyncSendMsg.sendOneMessage(userId,message,session);
    }

    /** 发送错误时的处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误,原因:"+error.getMessage());
        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) throws InterruptedException {

        while (sessionPool.get(userId)!= null&&sessionPool.get(userId).isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(2000);
        }
    }

    // 此为单点消息(多人)
    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();
                }
            }
        }

    }

}


@EnableAsync
@Component
public class AsynSendMsg {
    public Logger log = LogManager.getLogger(getClass());

    @Async
    public void sendOneMessage(String userId, String message,Session session) throws InterruptedException {
        while (WebSocket.getSessionPool().get(userId)!= null&&WebSocket.getSessionPool().get(userId).isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(1000);
        }
    }
}

解决服务器启动报错问题,若哪位大神有更好的解决办法留言私信我,谢谢

#修改方法(已测试)
将项目中引入的webSocket的jar包修改为

<dependency>
  	<groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
</dependency>
websocket定时信息推送可以通过以下步骤实现: 首先,需要在后端搭建一个websocket服务,可以使用常见的编程语言如Java、Node.js、Python等来实现。在服务端,我们可以使用一些库或框架来简化开发过程,如Java中的Spring WebSocket、Node.js中的Socket.io等。 接下来,在前端页面中引入websocket的客户端库,如使用JavaScript中的WebSocket API。通过该库,我们可以与后端的websocket服务器建立连接,并实现与服务器的实时双向通信。 为了实现定时信息推送,我们可以在后端设置一个定时任务,定时获取要推送的信息,并将其发送到客户端。具体实现方式可以根据实际需求来定,如可以在服务器启动时初始化一个定时器,或使用专门的定时任务库来处理。 在发送信息时,可以根据业务需求,选择将信息推送到单个客户端、指定的客户端组或者所有客户端。可以在后端维护一个客户端连接的集合,以便定向推送。 对于客户端,可以通过监听websocket的事件,如onmessage事件来接收服务器推送的信息。在接收到信息后,可以做相应的处理,如更新页面内容、弹出消息提示等。 需要注意的是,由于websocket是基于TCP协议的,所以在使用时需要考虑网络稳定性和负载均衡的问题,以提供更好的用户体验。 总结起来,websocket定时信息推送是一种实现实时双向通信的方式,通过后端websocket服务和前端websocket客户端,可以实现定时获取信息并推送到客户端,从而实现信息的实时更新和推送功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值