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


猜你喜欢
- 其实写到这里,我已经差不多断气了。。。常规套路,这里是前三篇的传送门,需要的同学可以看一下:JAVA写文本编辑器(三) JAVA写文本编辑器
- 可能我们用惯了 Newtonsoft.Json.dll 等第三方的类库来实现序列化等类似的操作,但是有时只是简单的用一下,感觉没必要那么费事
- 开发一款性能优良的应用是每一个Android开发者都必须经历的挑战。在移动端资源有限的前提下,提高应用的性能显得尤为重要。常见的提高APP性
- 目前的App在安装后,第一次打开,都会显示两秒左右的logo,然后进入引导页。如果关闭App,再重新打开,则只会显示logo,然后直接进入主
- 本文实例讲述了android同时控制EditText输入字符个数和禁止特殊字符输入的方法。分享给大家供大家参考。具体分析如下:这里总结了三种
- Unity3D的API提供了很多的功能,但是很多流程还是会自己去封装一下去。当然现在网上也有很多的框架可以去下载使用,但是肯定不会比自己写的
- 我也只是略懂皮毛,自己记录下方便以后看的,各位有任何高见烦请留言,谢谢,抱拳!想只复制值需要你的类实现ICloneable接口,并实现pub
- 前言 图片加水印:Springboot 图片需要添加水印,怎么办? 1秒就实现那么word文档替换文字、插入图片,当然也是1秒钟了
- 1:Maven命令下载源码和javadocs当在IDE中使用Maven时如果想要看引用的jar包中类的源码和javadoc需要通过maven
- 一、委托1、什么是委托委托是面向对象的、类型安全的,是引用类型。使用delegate关键字进行定义。委托的本质就是一个类,继承自System
- 方法1:C#Label1.Text = Request.Form["txtName"].ToString();vb.ne
- 本文实例讲述了eclipse中自动生成javadoc文档的方法。分享给大家供大家参考。具体方法如下:使用eclipse生成文档(javado
- 流程图 * vs过滤器 * 是SpringMVC的技术过滤器的Servlet的技术先过过滤器,过滤器过完才到DispatcherServle
- 前言本文准确来讲是探讨如何用 Jackson 来序列化 Apache avro 对象,因为简单用 Jackson 来序列化 Apache a
- 如下所示://读取json文件地址 /* String path = getClass().getClassLoader().g
- 无限滚动复用列表Demo展示前言游戏中有非常多的下拉滚动菜单,比如成就列表,任务列表,以及背包仓库之类;如果列表内容非常丰富,会占用大量内存
- 1. 背景介绍java中的数组比c语言中的数组,多了两个很重要的功能当索引越界时, 会自动抛出ArrayIndexOutOfBoundsEx
- Java接口回调产生接口回调的场景在现实生活中,产生接口回调的场景很简单,比如我主动叫你帮我做一件事,然后你做完这件事之后会通知我,&quo
- 1.定义Token的注解,需要Token校验的接口,方法上加上此注解import java.lang.annotation.ElementT
- MyBatis介绍MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software