SpringBoot 整合Netty-SocketIO实现信息推送

依赖

      <!--  及时通信服务 使用http协议实现ws长链接-->
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.18</version>
<!--            <version>1.7.7</version>-->
        </dependency>

配置文件

socketio:
  # host在本地测试可以设置为localhost或者本机IP,在Linux服务器跑可换成服务器IP
  host:  0.0.0.0
  # 端口号
  port: 8082
  # 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
  maxFramePayloadLength: 1048576
  # 设置http交互最大内容长度
  maxHttpContentLength: 1048576
  # socket连接数大小(如只监听一个端口boss线程组为1即可)
  bossCount: 1

  workCount: 100

  allowCustomRequests: true
  # 协议升级超时时间(毫秒),默认10秒。HTTP握手升级为ws协议超时时间
  upgradeTimeout: 1000000
  # Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件
  pingTimeout: 6000000
  # Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔
  pingInterval: 25000

信息体

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message implements Serializable {

	private static final long serialVersionUID = -5345570479231988220L;
	/**
	 * 发送人
	 */
	private String senderId;
	/**
	 * 接收人
	 */
	private String receiverId;
	/**
	 * 消息类型
	 */
	private String msgType;
	/**
	 * 消息体
	 */
	private Object content;

	/**
	 * 订阅的事件名称
	 */
	private String event;

	/**
	 * 创建的时间
	 */
	private String time;


}

NettySocketIOConfig 配置类

@Configuration
public class NettySocketIOConfig {

	@Value("${socketio.host}")
     private String host;

	 @Value("${socketio.port}")
     private Integer port;

	 @Value("${socketio.bossCount}")
     private int bossCount;

	@Value("${socketio.workCount}")
     private int workCount;

	 @Value("${socketio.allowCustomRequests}")
     private boolean allowCustomRequests;

	 @Value("${socketio.upgradeTimeout}")
     private int upgradeTimeout;

	 @Value("${socketio.pingTimeout}")
     private int pingTimeout;

	@Value("${socketio.pingInterval}")
     private int pingInterval;

	@Value("${socketio.maxFramePayloadLength}")
	private int maxFramePayloadLength;

	@Value("${socketio.maxHttpContentLength}")
	private int maxHttpContentLength;


    @Bean
   public SocketIOServer socketIOServer() {

	 com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
		// 开启Socket端口复用
		com.corundumstudio.socketio.SocketConfig socketConfig = new com.corundumstudio.socketio.SocketConfig();
		socketConfig.setReuseAddress(true);
		config.setSocketConfig(socketConfig);
		socketConfig.setTcpNoDelay(true);
		socketConfig.setSoLinger(0);
		         config.setSocketConfig(socketConfig);
		         config.setHostname(host);
		         config.setPort(port);
		         config.setBossThreads(bossCount);
		         config.setWorkerThreads(workCount);
		         config.setAllowCustomRequests(allowCustomRequests);
		         config.setUpgradeTimeout(upgradeTimeout);
		         config.setPingTimeout(pingTimeout);
		         config.setPingInterval(pingInterval);
		config.setMaxHttpContentLength(maxHttpContentLength);

		config.setMaxFramePayloadLength(maxFramePayloadLength);

		         return new SocketIOServer(config);
	}

	@Bean
	public SpringAnnotationScanner springAnnotationScanner() {
		return new SpringAnnotationScanner(socketIOServer());
	}

}

NettySocketIOServer 启动类 在Main方法执行之后立即执行

@Component
public class NettySocketIOServer implements CommandLineRunner {
	@Autowired
	private NettySocketIOService nettySocketIOService;

	@Override
	public void run(String... args) throws Exception {
		nettySocketIOService.start();
	}
}

NettySocketIOService接口

public interface NettySocketIOService {
	void  start();

	void stop();

	ResData<Map<String, Object>> sendMessage(Message message) throws Exception;
}

NettySocketIOService 接口实现类

@Component
@Slf4j
public class NettySocketIOServiceImpl implements NettySocketIOService {

	@Autowired
	private SocketIOServer socketIoServer;

	public static Map<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();

	@OnConnect
	public void onConnect(SocketIOClient client) {
		String uid = client.getHandshakeData().getSingleUrlParam("uid");
		socketIOClientMap.remove(uid);
		socketIOClientMap.put(uid, client);
	}

	@OnEvent("sendMsg")
	public void sendMsg(SocketIOClient socketIOClient, AckRequest ackRequest, Message data) {
log.info("接收到前端发来的数据:{}",data);
		if (data!= null) {
			// 全部发送
			socketIOClientMap.forEach((key, client) -> {
				if (client != null) {
					client.sendEvent("receiveMsg", JSONObject.toJSONString(data));
				}
			});
		}
	}





	/**
	 * 客户端断开
	 */
	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {
		String uid = client.getHandshakeData().getSingleUrlParam("uid");
		if(uid!=null){
			Set<String> keySet = socketIOClientMap.keySet();
			for (String key : keySet) {
				if(uid.equals(key)){
					SocketIOClient socketIOClient = socketIOClientMap.get(key);
				if(StrUtil.isBlankIfStr(socketIOClient)){
					socketIOClient.disconnect();
					log.info("用户 {} 端断开链接",uid);
				}

				}
			}
		}

	}




	@Override
	public void start() {
		socketIoServer.addEventListener("chatevent", Message.class, new DataListener<Message>() {
			@Override
			public void onData(SocketIOClient client, Message data, AckRequest ackRequest) {
				socketIoServer.getBroadcastOperations().sendEvent("chatevent", data);
			}
		});
		socketIoServer.start();
	}

	@Override
	public void stop() {
		socketIoServer.stop();
	}

	@Override
	public ResData<Map<String, Object>> sendMessage(Message message) throws Exception {
		String msg = JSONObject.toJSONString(message);

		return ResData.success("推送信息成功");
	}
}

前端代码

<template>
<div>
<el-button @click="sendMsg">发送</el-button>

</div>
</template>

<script>
import socketio from "socket.io-client";
// import {io} from "socket.io-client";  //高版本时

export default {
  name: "Test",
  data(){
    return{
      socket:null,
      message:{
        senderId:'',
        receiverId:'',
        msgType:'',
        content:'',
        event:'',
        time:''
      }
    }
  },mounted() {
    this.initSocketIO()
  },methods:{
    initSocketIO(){

       try {
         this.socket =  socketio.connect('http://localhost:8082?uid=1');

         this.socket.on('connect', function() {
           console.log('链接成功');
         });

         this.socket.on('receiveMsg', function(data) {

           console.log("服务器发送的消息是:"+data);
         });

         this.socket.on('disconnect', function () {
           console.log('socket断开连接');
         });
       }catch (e){
         console.log(e)
       }
    },

   sendMsg(){
     let data = new Date().toLocaleString();
     let fomatDate = data.replaceAll("/","-");
     this.message={
         senderId:'1',
         receiverId:'2',
         msgType:'0',
         content:'哈哈哈哈啊',
         event:'88',
         time:fomatDate
     }
     console.log(JSON.stringify(this.message))
     this.socket.emit('sendMsg',this.message);
}
  }
}
</script>

<style scoped>

</style>

注意: socket.io-client 版本太高可能不能使用,我最初使用高版本一直无法连接成功,后把它的版本降低至 "socket.io-client": "^2.4.0" 才连接成功

执行效果:

在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一个非常流行的Java开发框架,而Netty-socketio是一个基于Netty框架的WebSocket实现,提供了方便的实时通信解决方案。将它们结合起来,可以实现高效的WebSocket通信服务。 下面是整合的步骤: 1. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.corundumstudio.socketio</groupId> <artifactId>netty-socketio</artifactId> <version>1.7.16</version> </dependency> ``` 2. 编写Netty-socketio服务 创建一个类,继承自SpringBoot的ApplicationListener接口,用于启动Netty-socketio服务。 ``` import com.corundumstudio.socketio.Configuration; import com.corundumstudio.socketio.SocketIOServer; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class NettySocketIoServer implements ApplicationListener<ApplicationReadyEvent> { @Value("${socketio.host}") private String host; @Value("${socketio.port}") private Integer port; private SocketIOServer server; @Override public void onApplicationEvent(ApplicationReadyEvent event) { Configuration config = new Configuration(); config.setHostname(host); config.setPort(port); server = new SocketIOServer(config); server.start(); } } ``` 其中,@Value注解用于从配置文件中读取host和port的值,SocketIOServer是Netty-socketio提供的服务类,用于启动和管理WebSocket服务。 3. 配置WebSocket处理器 创建一个类,继承自Spring Boot的WebSocketHandler接口,用于处理WebSocket连接和消息。 ``` import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; @Component public class SocketIoHandler extends TextWebSocketHandler { @Autowired private SocketIOServer server; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); SocketIOClient client = server.getClient(session.getId()); if (client == null) { client = server.addClient(session); } } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); SocketIOClient client = server.getClient(session.getId()); if (client != null) { client.sendEvent("message", message.getPayload()); } } } ``` 其中,@Autowired注解用于从Spring容器中获取SocketIOServer实例,afterConnectionEstablished方法用于处理WebSocket连接建立时的逻辑,handleTextMessage方法用于处理WebSocket消息。 4. 配置WebSocket处理器映射 创建一个WebSocketHandlerRegistry类,用于配置WebSocket处理器的映射关系。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private SocketIoHandler socketIoHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(socketIoHandler, "/ws").setAllowedOrigins("*"); } } ``` 其中,@EnableWebSocket注解用于开启WebSocket支持,registerWebSocketHandlers方法用于配置WebSocket处理器映射关系。 5. 配置application.yml 在application.yml文件中添加以下配置: ``` socketio: host: localhost port: 8080 ``` 其中,host和port的值应与Netty-socketio服务的配置一致。 6. 运行程序 现在,可以运行程序,并访问http://localhost:8080/ws,即可建立WebSocket连接。发消息时,可以使用socket.emit()方法,接收消息时,可以使用socket.on()方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缘不易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值