WebSocket服务连接,推送消息

websocket服务端

配置pom文件,我这用的是1.5.13.RELEASE版本,可根据项目版本进行配置websocket服务版本

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

配置项目启动端口,可配可不配

server:
   port: 9999
   servlet:
     context-path: /demo

项目启动时,加载webconfig类,建立websocket服务

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
} 

配置websocket连接、关闭、发送服务

@ServerEndpoint("/websocket")
@Component
public class WebSocket {
    private final static Logger logger = LoggerFactory.getLogger(WebSocket.class);
    public static CopyOnWriteArraySet<WebSocket> flashWebSockets = new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        flashWebSockets.add(this);
        logger.debug("debug-socket开启");
        logger.debug("debug-目前连接人数:" + flashWebSockets.size());
    }

    @OnClose
    public void onClose() {
        flashWebSockets.remove(this);
        logger.debug("debug-socket关闭");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+message);
        System.out.println("-----------------------------------------------------------------------------------");
        logger.debug("debug-开启前端发送后台消息:" + message);
    }

    public void sendMessage(Object message) {
        try {
            String messageStr = JSON.toJSONString(message);
            this.session.getBasicRemote().sendText(messageStr);
            logger.debug(IPUtil.getLocalIPStr() + ":SOCKE-后端发消息到前端:" + messageStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
测试websocket服务发送数据,写个定时 每5秒推送一次数据,根据实际应用情况,来进行websokcet数据推送
  @Scheduled(cron = "*/5 * * * * ?")
    public void  test(){
        if (WebSocket.flashWebSockets.size() > 0) {
            for (WebSocket websoc : WebSocket.flashWebSockets) {
                try {
                    String s ="你好~溜达黄~";
//                    JSONObject jsonObject = JSONObject.parseObject(s);
                    websoc.sendMessage(s);
                    System.out.println("---服务端发送完成时间--- " + System.currentTimeMillis() + "------");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
以上是websocket服务端示例代码;

websocket服务端

开始配置websocket客户端,使用客户端去连接websocket服务端,并接收数据。
配置websocket注入方法
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

websocket客户端连接websocket服务端,连接地址为:ws://127.0.0.1:9999/demo/websocket

@Component
public class WebClient implements CommandLineRunner {
    //重连次数
    public static int retryTimes = 1;
    //websocket连接状态 webSocketType属性....1是断开连接..0是已经连接状态....
    public static int webSocketType = 0;
    private static Logger logger = LoggerFactory.getLogger(WebClient.class);

    @Override
    public void run(String... args) throws Exception {

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        MyClient client = new MyClient();
        try {
            logger.info("-----------------------webSocket开始连接-----------------------------------");
            container.connectToServer(client, new URI("ws://127.0.0.1:9999/demo/websocket"));
            webSocketType = 0;
            retryTimes = 1;
        } catch (Exception e) {
            //webSocketType = 1;
            e.printStackTrace();
            logger.info("---------------------------webSocket连接错误哦......----------------------------------");
        //    reConn();
        }
    }
//重连可要可不要,根据需要进行重连
    public void reConn() throws Exception {
        retryTimes++;
        if (retryTimes <= 3) {
            logger.info("---------websocket重连了----------" + retryTimes + "次........");
            new WebClient().run(null);
        }
    }
}

配置客户端接收数据方法,使用@ClientEndpoint注解来区分此服务为客户端服务

@ClientEndpoint
public class MyClient {

    //处理业务逻辑
    public static LinkedBlockingQueue lbq = new LinkedBlockingQueue(1000);//可指定容量,也可不指定

    private static Logger logger = LoggerFactory.getLogger(MyClient.class);
    public static CopyOnWriteArraySet<MyClient> flashWebSockets = new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen()
    public void open(Session session) {
        logger.info("Client WebSocket is opening...");
        this.session = session;
        session.setMaxTextMessageBufferSize(10 * 1024 * 1024);
        session.setMaxBinaryMessageBufferSize(10 * 1024 * 1024);
        flashWebSockets.add(this);
        logger.info("debug-socket开启:sessionId=" + session.getId());
        logger.info("debug-目前连接人数:" + flashWebSockets.size());
    }

    /**
     * 接收服务端发送的数据
     * @param message
     */
    @OnMessage(maxMessageSize = 1000000000)
    public void onMessage(String message) {
        try {

            System.out.println("接收数据:"+message);
//            JSONObject jsonObject = JSONObject.parseObject(message);
//            WebSocket.sendWebSocket(jsonObject);
            //数据多的时候放队列里面处理
            //lbq.put(jsonObject);
        }
         catch (Exception e) {
            logger.info("-----------------webSocket接收服务端数据出错了---------------" + e.getMessage());
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("-------------onError---发生错误:sessionId=" + session.getId() + "错误信息:" + error.getMessage());
    }
    
	//WebSocket服务关闭
    @OnClose
    public void onClose() {
        logger.info("--------------------WebSocket服务关闭------------------");
        flashWebSockets.remove(this);
        try {
            if (this.session != null) {
                logger.info("----------------onClose---sessionId=" + session.getId());
                this.session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        WebClient.webSocketType = 1;
        try {
            logger.info("-----------------开始重连------------------");
            WebClient.retryTimes = 1;
            new WebClient().run(null);
        } catch (Exception e) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>WebSocket服务关闭重连失败<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            e.printStackTrace();
        }
    }
    /**
     * 发送客户端消息到服务端
     *
     * @param message 消息内容
     */
    public void sendMessage(Object message) {
        try {
            String messageStr = JSON.toJSONString(message);
            this.session.getBasicRemote().sendText(messageStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }

以上配置好之后,启动服务端,在启动客户端,客户端连接成功后,会输出:websocket连接成功......”;
如果websocket服务端中,配置了定时发送任务,这时客户端会输出:你好~溜达黄~;
如果websocket服务端中,没有配置定时发送任务,则通过调用sendMessage(Object)方法发送数据信息。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值