springboot socketio
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>com.sys</groupId>
<artifactId>springboot-socketio</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot-socketio</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.corundumstudio.socketio/netty-socketio -->
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
2 启动加载 socket
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Component
@Order(value=)
public class MyCommandLineRunner implements CommandLineRunner {
private final SocketIOServer server; @Autowired
public MyCommandLineRunner(SocketIOServer server) {
this.server = server;
} @Override
public void run(String... args) throws Exception {
server.start();
System.out.println("socket.io启动成功!");
}
}
3 建立连接
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.util.ArrayList;
import java.util.Date;
import java.util.UUID; @Component
public class MessageEventHandler {
public static SocketIOServer socketIoServer;
public static ArrayList<UUID> listClient = new ArrayList<>();
//static final int limitSeconds = 60; @Autowired
public MessageEventHandler(SocketIOServer server) {
MessageEventHandler.socketIoServer = server;
} @OnConnect
public void onConnect(SocketIOClient client) {
listClient.add(client.getSessionId());
System.err.println(listClient.size());
System.out.println("客户端:" + client.getSessionId() + "已连接");
} @OnDisconnect
public void onDisconnect(SocketIOClient client) {
System.out.println("客户端:" + client.getSessionId() + "断开连接");
listClient.remove(client.getSessionId());
} @OnEvent(value = "messageevent") //value是监听事件的名称
public void onEvent(SocketIOClient client, AckRequest request, Object data) {
//System.out.println("发来消息:" + data.toString());
//socketIoServer.getClient(client.getSessionId()).sendEvent("messageevent", "back data"+new Date().getTime());
} public static void sendBuyLogEvent() { //这里就是向客户端推消息了
long dateTime = new Date().getTime(); for (UUID clientId : listClient) {
if (socketIoServer.getClient(clientId) == null) continue;
socketIoServer.getClient(clientId).sendEvent("messageevent", dateTime, );
}
} }
4 springboot 启动类SpringbootSocketioApplication 配置socket bean
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean; import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.sys.demo.kafka.KafkaSender; @SpringBootApplication
public class SpringbootSocketioApplication { public static void main(String[] args) {
ConfigurableApplicationContext context =SpringApplication.run(SpringbootSocketioApplication.class, args);
//SpringApplication.run(SpringBootKakfaApplication.class, args);
/*KafkaSender sender = context.getBean(KafkaSender.class); for (int i = 0; i < 3; i++) {
//调用消息发送类中的消息发送方法
sender.send(); try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */ }
@Bean
public SocketIOServer socketIOServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){ //在本地window环境测试时用localhost
System.out.println("this is windows");
config.setHostname("localhost");
} else {
config.setHostname("123.123.111.222"); //部署到你的远程服务器正式发布环境时用服务器公网ip
}
config.setPort(); /*config.setAuthorizationListener(new AuthorizationListener() {//类似过滤器
@Override
public boolean isAuthorized(HandshakeData data) {
//http://localhost:8081?username=test&password=test
//例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证
// String username = data.getSingleUrlParam("username");
// String password = data.getSingleUrlParam("password");
return true;
}
});*/ final SocketIOServer server = new SocketIOServer(config);
return server;
} @Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
} }
5 监听kafka 发送消息给客户端
package com.sys.demo.kafka; import java.util.Optional;
import java.util.UUID; import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component; import com.sys.demo.MessageEventHandler; @Component
public class KafkaReceiver {
@Autowired
private MessageEventHandler messageEventHandler;
@KafkaListener(topics = {"mycall_out"})
public void listen(ConsumerRecord<?, ?> record) {
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
Object message = kafkaMessage.get();
System.err.println("to client message:"+message);
for (UUID clientId : messageEventHandler.listClient) {
if (messageEventHandler.socketIoServer.getClient(clientId) == null)
continue;
//发送消息
messageEventHandler.socketIoServer.getClient(clientId).sendEvent("messageevent", message);
}
} }
}
springboot socketio的更多相关文章
- SpringBoot项目集成socketIo实现实时推送
netty-socketio maven依赖 <dependency> <groupId>com.corundumstudio.socketio</groupId> ...
- springBoot实现socketio
https://github.com/mrniko/netty-socketio-demo https://github.com/mrniko/netty-socketio
- netty-socketio(一)之helloworld,与springboot整合
netty-socketio是一个开源的Socket.io服务器端的一个java的实现, 它基于Netty框架. 1.参考资料 (1)netty-socketio项目github地址: https:/ ...
- netty-socketio整合springboot消息推送
netty-socketio整合springboot消息推送 1.netty-socketio消息推送 1)在项目中常常涉及到消息推送的情况,消息推送要求的实时性,使用传统的方式已经不能满足需求了: ...
- 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用
问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...
- 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo
Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...
- Springboot搭建web项目
最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了.关于springboot相关的介绍我就不赘述了,大家自行百度google. 一.pom配置 首先,建立一个maven项目,修 ...
- Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)
这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...
- 解决 SpringBoot 没有主清单属性
问题:SpringBoot打包成jar后运行提示没有主清单属性 解决:补全maven中的bulid信息 <plugin> <groupId>org.springframewor ...
随机推荐
- pytorch中使用cuda扩展
以下面这个例子作为教程,实现功能是element-wise add: (pytorch中想调用cuda模块,还是用另外使用C编写接口脚本) 第一步:cuda编程的源文件和头文件 // mathutil ...
- abort exit _exit return的区别
exit()函数导致子进程的正常退出,并且参数status&这个值将被返回给父进程.exit()应该是库函数.exit()函数其实是对_exit()函数的一种封装(库函数就是对系统调用的一种封 ...
- [转]Nodejs利用phantom 将html生成图片
原文地址:https://www.jianshu.com/p/8679f469e8d6 不过下载起来比较麻烦. 需要手动下载,然后将其添加到PATH中. 下载链接: https://sl-m-ssl. ...
- C# COM组的开发以及调用
一.用C#编写一个COM组件 1. 打开Visual Studio2008,[文件]->[新建]->[项目] 2. 项目类型=Visual C#,模版=类库,名称= ...
- Windows删除文件夹下的指定格式文件(递归删除)
问题描述: 今天遇到一个需求,需要对文件夹进行文件筛选.目录结构较为复杂(目录较多,层次较深),数据量较大(总共60GB左右). 鉴于上述情况,直接排除了人工处理方式(否则小伙伴们会打死我的). 解决 ...
- .net桌面程序或者控制台程序使用NLog时的注意事项
Nuget添加NLog 添加nlog.config文件,并选择属性->始终复制 不选择始终复制,编译后nlog.config是没有的. 具体使用: private static readonly ...
- 【并行计算-CUDA开发】GPU并行编程方法
转载自:http://blog.sina.com.cn/s/blog_a43b3cf2010157ph.html 编写利用GPU加速的并行程序有多种方法,归纳起来有三种: 1. 利用现有的G ...
- Mysql update多表联合更新
下面我建两个表,并执行一系列sql语句,仔细观察sql执行后表中数据的变化,很容易就能理解多表联合更新的用法 student表 ...
- IDEA的java源码文件左边有一个红色的J
解决办法: 如果源码文件这里已经有一个路径,那就添加现在的.java文件所在目录,或者删除了再重新添加
- Oracle--(Hierarchical Queries)层级查询(用于部门层级等)
原网址:https://www.cnblogs.com/guofeiji/p/5291486.html 如果表中包含层级数据,可以使用层级查询子句按层级顺序选择数据行,形成层级树,形式如下: 下面是层 ...