Spring Boot集成netty实现客户端服务端交互示例详解

这篇文章主要给大家介绍了关于Spring Boot集成netty实现客户端服务端交互的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

Netty 是一个性能的 NIO 网络框架,本文主要给大家介绍了关于SpringBoot集成netty实现客户端服务端交互的相关内容,下面来一起看看详细的介绍吧看了好几天的netty实战,慢慢摸索,虽然还没有摸着很多门道,但今天还是把之前想加入到项目里的一些想法实现了,算是有点信心了吧(讲真netty对初学者还真的不是很友好......)首先,当然是在SpringBoot项目里添加netty的依赖了,注意不要用netty5的依赖,因为已经废弃了io.nettynetty-all4.1.32.Final将端口和IP写入application.yml文件里,我这里是我云服务器的内网IP,如果是本机测试,用127.0.0.1就oknetty: port: 7000 url: 172.16.0.7在这之后,开始写netty的服务器,这里服务端的逻辑就是将客户端发来的信息返回回去因为采用依赖注入的方法实例化netty,所以加上@Component注释package com.safelocate.app.nettyServer; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; @Component public class NettyServer { //logger private static final Logger logger = Logger.getLogger(NettyServer.class); public void start(InetSocketAddress address){ EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup,workerGroup) .channel(NioServerSocketChannel.class) .localAddress(address) .childHandler(new ServerChannelInitializer()) .option(ChannelOption.so_BACKLOG, 128) .childOption(ChannelOption.so_KEEPALIVE, true); // 绑定端口,开始接收进来的连接 ChannelFuture future = bootstrap.bind(address).sync(); logger.info("Server start listen at " + address.getPort()); future.channel().closeFuture().sync(); } catch (Exception e) { e.printstacktrace(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }当然,这里的ServerChannelInitializer是我自己定义的类,这个类是继承ChannelInitializer的,里面设置出站和入站的编码器和解码器package com.safelocate.app.nettyServer; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.socketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ServerChannelInitializer extends ChannelInitializer { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8)); channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8)); channel.pipeline().addLast(new ServerHandler()); } }最好注意被别decoder和encoder写成了一样的,不然会出问题(我之前就是不小心都写成了StringDecoder...)在这之后就是设置ServerHandler来处理一些简单的逻辑了package com.safelocate.app.nettyServer; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.socket; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("channelActive----->"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server channelRead......"); System.out.println(ctx.channel().remoteAddress()+"----->Server :"+ msg.toString()); //将客户端的信息直接返回写入ctx ctx.write("server say :"+msg); //刷新缓存区 ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printstacktrace(); ctx.close(); } }准备工作到这里,现在要做到就是去启动这个程序将AppApplication实现CommandLineRunner这个接口,这个接口可以用来再启动SpringBoot时同时启动其他功能,比如配置,数据库连接等等然后重写run方法,在run方法里启动netty服务器,Server类用@AutoWired直接实例化package com.safelocate.app; import com.safelocate.app.nettyServer.NettyServer; import io.netty.channel.ChannelFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.net.InetAddress; import java.net.InetSocketAddress; @SpringBootApplication public class AppApplication implements CommandLineRunner { @Value("${netty.port}") private int port; @Value("${netty.url}") private String url; @Autowired private NettyServer server; public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } @Override public void run(String... args) throws Exception { InetSocketAddress address = new InetSocketAddress(url,port); System.out.println("run .... . ... "+url); server.start(address); } }ok,到这里服务端已经写完,本地我也已经测试完,现在需要打包部署服务器,当然这个程序只为练手...控制台输入mvn clean package -D skipTests 然后将jar包上传服务器,在这之后,需要在腾讯云/阿里云那边配置好安全组,将之前yml文件里设定的端口的入站规则设置好,不然访问会被拒绝之后java -jar命令运行,如果需保持后台一直运行 就用nohup命令,可以看到程序已经跑起来了,等待客户端连接交互

之后就是写客户端了,客户端其实是依葫芦画瓢,跟上面类似Handlerpackage client; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("ClientHandler Active"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("--------"); System.out.println("ClientHandler read Message:"+msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printstacktrace(); ctx.close(); } }ChannelInitializerpackage client; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.socketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ClientChannelInitializer extends ChannelInitializer { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new ClientHandler()); } }主函数所在类,即客户端package client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.socketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class Client { static final String HOST = System.getProperty("host", "服务器的IP地址"); static final int PORT = Integer.parseInt(System.getProperty("port", "7000")); static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); public static void main(String[] args) throws Exception { sendMessage("hhhh"); } public static void sendMessage(String content) throws InterruptedException{ // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder()); p.addLast("encoder", new StringEncoder()); p.addLast(new ClientHandler()); } }); ChannelFuture future = b.connect(HOST, PORT).sync(); future.channel().writeAndFlush(content); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }启动客户端,这里就是简单发送一条"hhhh",可以看到客户端已经收到服务器发来的信息

然后再看服务端,也有相应的信息打印

总结以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...