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 ...
随机推荐
- qt model/view/delegate
Qt Model/View理解(一)---构造model https://blog.csdn.net/weixin_42303052/article/details/89233887 Qt Model ...
- Centos7安装文件传输软件rz sz
一直使用Xshell的xftp传输文件,谁知道忽然无法正常使用. 于是,决定用户rz进行传输 安装步骤也比较简单 1.首先安装第三方源(以下源比默认源包含更多安装包,建议添加该源使用) yum ins ...
- 头部文件jq嵌入笔记
var headHtml = '<div class="container">' + '<div class="navbar-header"& ...
- 最新 多点Dmalljava校招面经 (含整理过的面试题大全)
从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.多点Dmall等10家互联网公司的校招Offer,因为某些自身原因最终选择了多点Dmall.6.7月主要是做系统复习.项目复 ...
- 【问题】Could not locate PropertySource and the fail fast property is set, failing
这是我遇到的问题 Could not locate PropertySource and the fail fast property is set, failing springcloud的其他服务 ...
- kafka-manager 创建 topic【转】
1,add cluster 添加cluster 添加cluster 选择一下kafka的版本 2,创建topic 添加topic 3,查看topic 查看topic
- UV数据与风速风向数据转换
package com.qr.util; import java.text.DecimalFormat; /** * //TODO UV数据与风速风向数据转换 */ public class UVAn ...
- MSSQLSERVER 服务运行内存设置较小导致启动服务失败
问题产生原因: 手动设置MSSQLSERVER 运行内存,设置值未达到MSSQLSERVER 服务运行内存最低值(max server memory 所允许的最小内存量是 128 MB.),导致MSS ...
- python_并发与通信
独立的进程内存空间与共享的服务器进程空间 知识点一: 进程间通信的限制 进程是独立的,互不干扰的独立内存空间我们想不能修改变量但是,深层次问题是,这个进程与那个进程完全失去了联系 import mul ...
- 全栈项目|小书架|服务器端-NodeJS+Koa2实现首页图书列表接口
通过上篇文章 全栈项目|小书架|微信小程序-首页水平轮播实现 我们实现了前端(小程序)效果图的展示,这篇文章来介绍服务器端的实现. 首页书籍信息 先来回顾一下首页书籍都有哪些信息: 从下面的图片可以看 ...