Springboot中使用netty 实现 WebSocket 服务

这篇具有很好参考价值的文章主要介绍了Springboot中使用netty 实现 WebSocket 服务。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

依赖


    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.77.Final</version>
    </dependency>
创建启动类
package com.message.after;

import com.message.websocket.WebSocketServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author kuaiting
 */
@Component
public class AfterExecuteMethods implements CommandLineRunner {
	/**
	 * 项目启动之后立即执行的方法,可以做些初始化项目的操作以及需要启动项目立即执行的任务
	 * @param args
	 * @throws Exception
	 */
	@Override
	public void run(String... args) throws Exception {
		/**
		 * 启动WebSocketServer 服务使用netty实现
		 */
		new WebSocketServer().start();
	}
}

创建WebSocket 服务
package com.message.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author kuaiting
 * WebSocket
 */

public class WebSocketServer {


	public void start() {
		// 一个主线程组
		NioEventLoopGroup mainGroup = new NioEventLoopGroup();
		//一个工作线程组
		NioEventLoopGroup subGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(mainGroup, subGroup)
					//设置队列大小
					.option(ChannelOption.SO_BACKLOG, 1024)
					.channel(NioServerSocketChannel.class)
					// 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					//添加自定义初始化处理器
					.childHandler(new WsServerInitialzer());
			ChannelFuture channelFuture = serverBootstrap.bind(8082).sync();
			channelFuture.channel().closeFuture().sync();

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			//关闭主线程组
			mainGroup.shutdownGracefully();
			//关闭工作线程组
			subGroup.shutdownGracefully();
		}


	}
}

WsServerInitialzer 初始化
package com.message.websocket;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author kuaiting
 */
public class WsServerInitialzer extends ChannelInitializer<SocketChannel> {
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {

		ChannelPipeline pipeline = ch.pipeline();
		//websocket基于http协议,所以需要http编解码器
		pipeline.addLast(new HttpServerCodec());
		//添加对于读写大数据流的支持
		pipeline.addLast(new ChunkedWriteHandler());
		//对httpMessage进行聚合
		pipeline.addLast(new HttpObjectAggregator(1024*64));

		// ================= 上述是用于支持http协议的 ==============

		//websocket 服务器处理的协议,用于给指定的客户端进行连接访问的路由地址
		//比如处理一些握手动作(ping,pong)
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		//自定义handler
		pipeline.addLast(new ChatHandler());

	}
}

创建信息ChatHandler 处理类
package com.message.websocket;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kuaiting
 */
@Slf4j
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	private static  ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("已创建WebSocket链接:{}", ctx.channel().remoteAddress());
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		String text = msg.text();
		sendAllMessages(ctx,text);
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		channels.add(ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		log.info("断开链接的ID", ctx.channel().id().asLongText());

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().closeFuture();
	}


	//给每个人发送消息,除发消息人外
	private void sendAllMessages(ChannelHandlerContext ctx, String msg) {
		for (Channel channel : channels) {
			if (!channel.id().asLongText().equals(ctx.channel().id().asLongText())) {
				channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
			}
		}
	}

	//给每个人发送消息,除发消息人外
	private void sendMessages(String msg) {
		for (Channel channel : channels) {
			channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
		}
	}

}

文章来源地址https://www.toymoban.com/news/detail-619614.html

到了这里,关于Springboot中使用netty 实现 WebSocket 服务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 基于Springboot用Netty实现WebSocket及用户身份校验

    说在前头,文本主要参考: SpringBoot+WebSocket+Netty实现消息推送 Netty-11-channelHandler的生命周期 springboot整合netty指北 首先 需要了解下channel建立的生命周期 ChannelHandler的顺序如下: 注意本次实现的重点是:在建立websocket时从请求标头header或者第一次消息对话时获取用户信息(如jw

    2024年02月04日
    浏览(9)
  • springBoot + netty搭建高性能 websocket 服务 & 性能测试(包含python 测试脚本)

    springBoot + netty搭建高性能 websocket 服务 & 性能测试(包含python 测试脚本)

    1、如果我们的app类似于股票这种,数据很多很快,之前用的tomcat自带的 websocket 又或者 spring-boot-starter-websocke 集成,但是性能在数据并发很大时就会存在问题。 2、我前面写的一篇关于 springBoot+webosket的,没有使用netty的文章 springBoot使用webSocket的几种方式以及在高并发出现的

    2024年02月04日
    浏览(13)
  • 基于Springboot+WebSocket+Netty实现在线聊天、群聊系统

    基于Springboot+WebSocket+Netty实现在线聊天、群聊系统

    此文主要实现在好友添加、建群、聊天对话、群聊功能,使用Java作为后端语言进行支持,界面友好,开发简单。 2.1、下载安装IntelliJ IDEA(后端语言开发工具),Mysql数据库,微信Web开发者工具。 1.创建maven project 先创建一个名为SpringBootDemo的项目,选择【New Project】 然后在弹出

    2024年02月14日
    浏览(18)
  • SpringBoot项目整合WebSocket+netty实现前后端双向通信(同时支持前端webSocket和socket协议哦)

    SpringBoot项目整合WebSocket+netty实现前后端双向通信(同时支持前端webSocket和socket协议哦)

    目录   前言 技术栈 功能展示 一、springboot项目添加netty依赖 二、netty服务端 三、netty客户端 四、测试 五、代码仓库地址   专属小彩蛋:前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站(前言 - 床长人工智能教程

    2024年02月12日
    浏览(8)
  • SpringBoot中使用Netty实现TCP通讯,服务器主动向客户端发送数据

    SpringBoot中使用Netty实现TCP通讯,服务器主动向客户端发送数据

    Springboot项目的web服务后台,web服务运行在9100端口。 后台使用netty实现了TCP服务,运行在8000端口。 启动截图如下: 启动类修改: 服务器查看当前所有连接的客户端  服务器获取到所有客户单的ip地址及端口号后,即可通过其给指定客户端发送数据  

    2024年02月11日
    浏览(14)
  • 服务端(后端)主动通知前端的实现:WebSocket(springboot中使用WebSocket案例)

    我们都知道 http 协议只能浏览器单方面向服务器发起请求获得响应,服务器不能主动向浏览器推送消息。想要实现浏览器的主动推送有两种主流实现方式: 轮询:缺点很多,但是实现简单 websocket:在浏览器和服务器之间建立 tcp 连接,实现全双工通信 springboot 使用 websocket 有

    2023年04月14日
    浏览(22)
  • 【项目实战】基于netty-websocket-spring-boot-starter实现WebSocket服务器长链接处理

    【项目实战】基于netty-websocket-spring-boot-starter实现WebSocket服务器长链接处理

    项目中需要建立客户端与服务端之间的长链接,首先就考虑用WebSocket,再来SpringBoot原来整合WebSocket方式并不高效,因此找到了netty-websocket-spring-boot-starter 这款脚手架,它能让我们在SpringBoot中使用Netty来开发WebSocket服务器,并像spring-websocket的注解开发一样简单 2.1.1 @ServerEndpo

    2024年02月12日
    浏览(10)
  • Springboot整合Netty实现RPC服务器

    Springboot整合Netty实现RPC服务器

    try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker) .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 60)); pipeline.addLast(new JsonDecoder()); pipeline.addLast(new JsonEnco

    2024年04月09日
    浏览(13)
  • Springboot+Netty+WebSocket搭建简单的消息通知

    Springboot+Netty+WebSocket搭建简单的消息通知 一、快速开始 1、添加依赖 2、添加配置 3、添加启动类 二、添加WebSocket部分代码 1、WebSocketServer 2、WebSocketConfig 3、DemoController 6、添加templates/index.html 三、添加Netty部分 1、NettyServer 2、WSChannelHandlerPool 3、WSWebSocketHandler 四、启动服务 ht

    2024年02月11日
    浏览(9)
  • netty学习(3):SpringBoot整合netty实现多个客户端与服务器通信

    netty学习(3):SpringBoot整合netty实现多个客户端与服务器通信

    创建一个SpringBoot工程,然后创建三个子模块 整体工程目录:一个server服务(netty服务器),两个client服务(netty客户端) pom文件引入netty依赖,springboot依赖 NettySpringBootApplication NettyServiceHandler SocketInitializer NettyServer NettyStartListener application.yml Client1 NettyClientHandler SocketInitializ

    2024年02月11日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包