SpringBoot集成netty实现客户端服务端交互⽰例详解前⾔
Netty 是⼀个⾼性能的 NIO ⽹络框架,本⽂主要给⼤家介绍了关于SpringBoot集成netty实现客户端服务端交互的相关内容,下⾯来⼀起看看详细的介绍吧
看了好⼏天的netty实战,慢慢摸索,虽然还没有摸着很多门道,但今天还是把之前想加⼊到项⽬⾥的
⼀些想法实现了,算是有点信⼼了吧(讲真netty对初学者还真的不是很友好......)
⾸先,当然是在SpringBoot项⽬⾥添加netty的依赖了,注意不要⽤netty5的依赖,因为已经废弃了
<!--netty-->
<dependency>
<groupId>ioty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
将端⼝和IP写⼊l⽂件⾥,我这⾥是我云服务器的内⽹IP,如果是本机测试,⽤127.0.0.1就ok
netty:
port: 7000
url: 172.16.0.7
在这之后,开始写netty的服务器,这⾥服务端的逻辑就是将客户端发来的信息返回回去
因为采⽤依赖注⼊的⽅法实例化netty,所以加上@Component注释
package com.safelocate.apptyServer;
import ioty.bootstrap.ServerBootstrap;
import ioty.channel.*;
import ioty.channel.nio.NioEventLoopGroup;
import ioty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import java.InetSocketAddress;
@Component
public class NettyServer {
//logger
private static final Logger logger = Logger(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)spring boot依赖注入原理
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 绑定端⼝,开始接收进来的连接
ChannelFuture future = bootstrap.bind(address).sync();
logger.info("Server start listen at " + Port());
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
当然,这⾥的ServerChannelInitializer是我⾃⼰定义的类,这个类是继承ChannelInitializer<SocketChannel>的,⾥⾯设置出站和⼊站的编码器和解码器
package com.safelocate.apptyServer;
import ioty.channel.ChannelInitializer;
import ioty.channel.socket.SocketChannel;
import dec.string.StringDecoder;
import dec.string.StringEncoder;
import ioty.util.CharsetUtil;
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
@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写成了⼀样的,不然会出问题(我之前就是不⼩⼼都写成了)
在这之后就是设置ServerHandler来处理⼀些简单的逻辑了
package com.safelocate.apptyServer;
import ioty.channel.ChannelHandlerContext;
import ioty.channel.ChannelInboundHandlerAdapter;
import ioty.channel.SimpleChannelInboundHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.InetAddress;
import java.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("");
System.out.println(ctx.channel().remoteAddress()+"----->Server :"+ String());
//将客户端的信息直接返回写⼊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.apptyServer.NettyServer;
import ioty.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.InetAddress;
import java.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 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命令,可以看到程序已经跑起来了,等待客户端连接交互
之后就是写客户端了,客户端其实是依葫芦画瓢,跟上⾯类似
Handler
package client;
import ioty.channel.ChannelHandlerContext;
import ioty.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();
}
}
ChannelInitializer
package client;
import ioty.channel.ChannelInitializer;
import ioty.channel.ChannelPipeline;
import ioty.channel.socket.SocketChannel;
import dec.string.StringDecoder;
import dec.string.StringEncoder;
import ioty.util.CharsetUtil;
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
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 ioty.bootstrap.Bootstrap;
import ioty.channel.*;
import ioty.channel.nio.NioEventLoopGroup;
import ioty.channel.socket.SocketChannel;
import ioty.channel.socket.nio.NioSocketChannel;
import dec.string.StringDecoder;
import dec.string.StringEncoder;
public class Client {
static final String HOST = Property("host", "服务器的IP地址");
static final int PORT = Integer.Property("port", "7000"));
static final int SIZE = Integer.Property("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();
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@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",可以看到客户端已经收到服务器发来的信息
然后再看服务端,也有相应的信息打印
总结
以上就是这篇⽂章的全部内容了,希望本⽂的内容对⼤家的学习或者⼯作具有⼀定的参考学习价值,如果有疑问⼤家可以留⾔交流,谢谢⼤家对的⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。