SpringBoot集成Netty实现简单通信

演示效果:

一:Netty简介

Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。

Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。

这是官方的一个阐述,简而言之来说就是一套高性能 支持高并发场景下的通信中间件。

 

二:SpringBoot集成Netty

1: 新建项目 引入相关依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--    集成Netty    -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.25.Final</version>
        </dependency>

2:新建Netty服务端实例 (WebSocketNettyServer)

package com.cposnettyim.cposim.im;

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

/**
 * @auth Lxl
 * @since 2021/1/30
 */
public class WebSocketNettyServer {

    public static void main(String[] args) {
           //创建两个线程
           NioEventLoopGroup mainGrp = new NioEventLoopGroup(); //主线程池
           NioEventLoopGroup subGrp = new NioEventLoopGroup(); //从线程池

          try {
              //创建Netty服务器启动对象
              ServerBootstrap bootstrap = new ServerBootstrap();

              //创建服务器启动对象
              bootstrap
                      //指定上述定义的主从线程
                      .group(mainGrp, subGrp)
                      //指定Netty通道类型
                      .channel(NioServerSocketChannel.class)
                      //指定通道初始化器用来加载当Channel收到消息事件后 如何进行业务处理
                      .childHandler(new WebsocketChannelInitializer());
              //绑定服务器端口
              ChannelFuture future = bootstrap.bind(9066);
              //等待服务器关闭
              future.channel().closeFuture().sync();
          }catch (Exception e){
               e.printStackTrace();
          }finally {
              //关闭服务器
              mainGrp.shutdownGracefully();
              subGrp.shutdownGracefully();
          }

    }
}

3:新增Netty通道初始化器

package com.cposnettyim.cposim.im;

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;

/**
 * @auth Lxl
 * @since 2021/1/30
 *
 *  通道初始化器
 */
public class WebsocketChannelInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        //获取管道
        ChannelPipeline pipeline = socketChannel.pipeline();

        //设置http编解码器
        pipeline.addLast(new HttpServerCodec());
        //设置用于支持大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //设置聚合器合器主要讲HttpMessage聚合成FullHttpRequest/Response
        pipeline.addLast(new HttpObjectAggregator(1024*64));


        //指定接手对应的路由信息
        //必须使用ws后缀结尾的url才接收处理
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        //设置自定义的Handler
        pipeline.addLast(new MyChatHandler());


    }

}

4:自定义Handlder处理数据

package com.cposnettyim.cposim.im;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
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 java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auth Lxl
 * @since 2021/1/30
 *   自定义Handlder
 */
public class MyChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用来保存所有客户端连接
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sdf =new SimpleDateFormat("YYYY-MM-dd HH:mm");

    //当通道(channel)内有新的消息会自动调用
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
         //获取客户端发送过来的文本消息
        String text = msg.text();
        System.out.println("接收到的消息:"+text);

       for(Channel channel : clients){
           String asLongText = channel.id().asLongText().substring(0,6);
           channel.writeAndFlush(new TextWebSocketFrame(asLongText+"&"+sdf.format(new Date())+"&"+text));
       }
    }

    //当有新的客户端连接服务器后 会自动调用这个方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }
}

5: 启动 测试!

1:web聊天界面默认地址:http://127.0.0.1:20999/Mychat.html

2:Netty服务地址:ws://127.0.0.1:9066/ws  (前台调试)

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<head>
    <meta charset="UTF-8">
    <title>CposIM在线聊天</title>
</head>
<link rel="icon" type="image/png" sizes="144x144" href="/icon/icon.png"/>
<link rel="apple-touch-icon" type="image/png" sizes="144x144" href="/icon/icon.png"/>
<body style="background-image: url('/img/imbk.jpg') ">
<center>
<input type="text"  style="width: 420px;height: 40px;font-size: 15px" id ="message">
<input type="button" style="width:100px; height:46px;" value ="发送消息" onclick="sendMsg()">
    <div style="width: 632px;height:1000px;border-color: aqua ">
        <p id="server_message" style="background-color: blanchedalmond;float:left;padding-left:5px;padding-right:120px;padding-top:20px;"></p>
    </div>
</center>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
    var websocket =null;
    //浏览器是否支持websocket
    if(window.WebSocket){
        websocket = new WebSocket("ws://zvck7r.natappfree.cc/ws");
        websocket.onopen = function () {
            console.log("建立连接");
        }
        websocket.onclose = function () {
            console.log("断开连接");
        }
        websocket.onmessage = function (e) {
            console.log("接收到服务器消息:"+e.data.split("&"));
            var name = e.data.split("&")[0];
            var date = e.data.split("&")[1];
            var text = e.data.split("&")[2];

            var server_message = document.getElementById("server_message");
            //"用户:"+name+
            server_message.innerHTML +="&nbsp;&nbsp;&nbsp;&nbsp;时间:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+date+"&nbsp;&nbsp;<br/>内容:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                "<span style='color: red'>"+text+"</span><br/>";
        }
    } else {
        alert("暂不支持webSocket");
    }

    //回车键发送消息
    $('#message').bind('keypress',function(event){
        sendMsg()
    });

    function sendMsg(){
        var message = document.getElementById("message");
        websocket.send(message.value);
    }
</script>
</body>
</html>

6:外网访问(配置内网穿透 修改地址)

为什么要提到外网访问呢? 因为这个地方容易踩坑,很多时候本地局域网测试了 然后拿到手机上一试发现点击的发送消息并没反应 其实就是本地地址需要配置成传统地址才能访问

推荐两块免费的内网穿透工具 超级好用! Natapp 和  Sunny-Ngrok 操作很便捷 可以将内网直接映射成外网访问 这样手机也能实时在线聊天了

穿透两个地址: 一个是Socket的服务地址  另外一个就是web页面访问地址了 记得穿透完以后改地址

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Boot集成Netty可以实现TCP协议的通信Netty是一个高性能、异步事件驱动的网络应用框架,可以用于开发各种协议的服务器和客户端。在Spring Boot中,可以通过添加Netty依赖和配置Netty的相关参数来实现TCP通信。具体实现方式可以参考相关文档和示例代码。 ### 回答2: Spring Boot是一种快速开发框架,旨在简化应用程序的开发和部署过程。Netty是一个事件驱动的网络应用程序框架。它允许您快速构建高性能和可扩展的网络应用程序。在本文中,我们将探讨如何使用Spring Boot集成Netty实现TCP。 首先,我们需要在pom.xml文件中添加Netty和Spring Boot的依赖。这有助于我们在代码中使用Spring Boot和Netty的类和方法。例如,我们需要添加以下依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.57.Final</version> </dependency> </dependencies> ``` 接下来,我们将创建一个Netty服务器类来处理传入的TCP连接。以下是一个简单Netty服务器类: ```java @Component public class NettyServer { private final int port; @Autowired public NettyServer(@Value("${netty.port:8000}") int port) { this.port = port; } public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new NettyServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 100) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 在此代码中,我们创建了一个Netty服务器来处理传入的TCP连接。我们使用@Value注释将端口号设置为默认值8000。在start()方法中,我们创建了两个事件循环组,一个用于接受传入连接,另一个用于处理连接。我们还将服务器绑定到指定的端口,并在服务器关闭时优雅地关闭事件循环组。 接下来,我们需要创建一个Netty处理程序类来处理传入的数据。以下是一个简单Netty处理程序类: ```java @Component public class NettyServerHandler extends SimpleChannelInboundHandler<String> { @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Received message: " + msg); ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 在这个代码中,我们创建了一个Netty服务器处理程序类来处理传入的数据。我们使用SimpleChannelInboundHandler类来处理数据。在channelRead0()方法中,我们打印接收到的消息并将消息写回客户端。在channelReadComplete()方法中,我们将缓冲区的所有数据刷新到远程节点并关闭通道。在exceptionCaught()方法中,我们打印了异常堆栈并关闭通道。 最后,我们需要创建一个Spring Boot应用程序类来启动Netty服务器。以下是一个简单的Spring Boot应用程序类: ```java @SpringBootApplication public class Application { public static void main(String[] args) throws InterruptedException { SpringApplication.run(Application.class, args); NettyServer server = new NettyServer(8000); server.start(); } } ``` 在此代码中,我们启动了Spring Boot应用程序并创建了一个Netty服务器对象。我们在启动服务器时将端口号设置为8000。注意,我们使用的是阻塞式服务器,并且它会阻塞主线程,直到服务器被关闭。 综上所述,我们使用Spring Boot集成Netty实现了TCP。我们创建了一个Netty服务器类来处理传入的TCP连接,一个Netty处理程序类来处理传入的数据,最后创建了一个Spring Boot应用程序类来启动Netty服务器。 ### 回答3: Spring Boot是一套快速开发框架,它可以帮助开发人员更快速、更高效地开发应用程序。而Netty是一个高性能的网络框架,可以实现异步、事件驱动的网络编程。将Spring Boot和Netty结合在一起,可以实现快速构建高性能的网络应用程序。 想要将Spring Boot集成Netty实现TCP,有以下几个步骤: 1. 添加Netty依赖:在pom.xml中添加Netty的依赖,可以从官网上找到最新版本的依赖。 2. 编写Netty处理器:首先需要编写一个Netty的处理器类,来处理客户端的请求。处理器类需要实现Netty的ChannelInboundHandler接口,并重写其中的channelRead方法,在该方法中处理来自客户端的数据。 3. 配置Netty服务器:在程序的入口类中,创建Netty服务器并配置相关参数,如端口号、主机地址等。同时,需要将编写的处理器类设置进来,以便在接收到客户端的请求时能够正确调用。 4. 运行程序:配置好之后,可以运行程序,测试TCP协议的功能是否正常。此时可以使用各种工具进行测试,如Telnet、Putty等。 综上所述,使用Spring Boot集成Netty实现TCP,可以大大简化应用程序的开发流程,同时也能够实现高性能的网络编程。如果开发人员想要实现更复杂的网络应用程序,可以在Netty处理器中添加更多的功能逻辑,并根据具体的业务需求进行开发。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

凌玄剑君

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

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

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

打赏作者

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

抵扣说明:

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

余额充值