Java中websocket消息推送的实现代码
作者:tianzhongshan 发布时间:2023-06-02 09:26:56
标签:websocket,消息,推送
一.服务层
package com.demo.websocket;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Configuration
@EnableWebSocket
public class websocketListener implements WebSocketConfigurer, ServletContextListener{
private ConcurrentLinkedQueue<WebSocketSession> sessions = new ConcurrentLinkedQueue<WebSocketSession>();
private WebSocketHandlerTest handler;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
handler = new WebSocketHandlerTest();
registry.addHandler(handler, "/ws/notifymessage.ws");
registry.addHandler(handler, "/ws/sockjs/notifymessage.ws").withSockJS();
new Thread(handler).start();
}
class WebSocketHandlerTest extends TextWebSocketHandler implements Runnable{
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
super.handleTextMessage(session, message);
}
@Override
public void run() {
System.out.println("等待推送....");
try {
int i = 0;
for (;;) {
synchronized (this) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i%10==0){
nofity("消息推送测试......");
System.out.println("推送消息了....");
}else{
System.out.println("本次不推送消息了....");
}
i++;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("失败....");
}
}
private void nofity(String message) throws IOException {
Iterator<WebSocketSession> iterator = sessions.iterator();
while (iterator.hasNext()) {
WebSocketSession session = iterator.next();
synchronized(session){
if(session.isOpen()){
session.sendMessage(new TextMessage(message));
}else{
iterator.remove();
}
}
}
}
}
}
二.前台界面监听
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
websocket测试界面
</body>
<script type="text/javascript">
var websocketPath = "localhost:8080/demo-web";
if ('WebSocket' in window) {
websocket = new WebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
} else {
websocket = new SockJS("ws://"+websocketPath+"/ws/notifymessage.ws");
}
websocket.onopen = function (evnt) {
};
websocket.onmessage = function (evnt) {
console.log(evnt);
};
websocket.onerror = function (evnt) {
};
websocket.onclose = function (evnt) {
}
</script>
</html>
注意web.xml中配置DispatcherServlet控制器
spring-servlet.xml空文件
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.ws</url-pattern>
</servlet-mapping>
以上所述是小编给大家介绍的Java中websocket消息推送的实现代码网站的支持!
来源:http://www.cnblogs.com/tianzhongshan/archive/2017/02/13/6392752.html
0
投稿
猜你喜欢
- 最近有由于需要,我开始接触阿里云的云市场的印刷文字识别-营业执照识别这里我加上了官网的申请说明,只要你有阿里云账号就可以用,前500次是免费
- 本文实例为大家分享了Android绝对布局AbsoluteLayout的具体代码,供大家参考,具体内容如下1>AbsoluteLayo
- 1.发生问题的场景我在用java获取一个接口的大JSON字符串,并赋值给String常量时,遇到了java: 常量字符串过长这个报错2.解决
- 一、二叉搜索树插入元素/** * user:ypc; * date:2021-05-18; * time: 15:09; */
- 1、运算符两边的变量为boolean变量时 先列出代码:public clas
- 目录Spring是什么?Spring Boot是什么?Maven依赖项springboot为不同的Spring模块提供了许多启动程序依赖项。
- 概述ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存。ArrayList不是
- 这篇文章主要介绍了Spring ApplicationListener * 用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具
- 一、ReentrantLock可重入锁可重入锁ReentrantLock 是一个互斥锁,即同一时间只有一个线程能够获取锁定资源,执
- —举例(学生排课)—正常思路的处理方法和优化过后的处理方法:比如说给学生排课。学生和课程是一个多对多的关系。按照正常的逻辑 应该有一个关联表
- jpa EntityManager复杂查询概念EntityManager:EntityManager是JPA中用于增删改查的接口,它的作用相
- 一条SQL使用两个foreach的问题未修改前的 SQL 语句<select id="findQuestionType_3_
- 背景在研究规则引擎时,如果规则以文件的形式存储,那么就需要监听指定的目录或文件来感知规则是否变化,进而进行加载。当然,在其他业务场景下,比如
- 介绍Java中的享元模式(Flyweight Pattern)是一种结构型设计模式,旨在通过共享尽可能多的对象来减少内存占用和提高性能.Ja
- @CompentScan excludeFilters配置无效@CompentScan 注解配置需要扫描的包excludeFilters 是
- 前言 今天在看Android ContentProvider实现的时候,突然想到了Java类在new的过
- 说明在学习jvm相关知识时,一般会讲到类字节码相关内容,为了更清晰的了解类字码具体内容,一般我们会使用javap命令进行查看,但是仍然不够直
- 本文实例为大家分享了Android下载进度监听和通知的具体代码,供大家参考,具体内容如下下载管理器关于下载进度的监听,这个比较简单,以apk
- 学习Java 本身是一个挺枯燥的过程,说白了就是每天敲代码而已。但如果换一种思路,可以编写各种各样的程序,不仅加深对代码的理解,同时提高兴趣
- 以前就遇到过这个问题,今天重新拾起来。跑马灯效果其实就是当文字超过TextView控件宽度的时候,使用滚动的方式显示出来:方法1:(直接xm