一、maven配置
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.9.RELEASEversion>
<relativePath />
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<skipTests>trueskipTests>
<fastjson.version>1.2.31fastjson.version>
<netty.version>4.1.6.Finalnetty.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
<scope>truescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastjson.version}version>
dependency>
<dependency>
<groupId>io.nettygroupId>
<artifactId>netty-allartifactId>
<version>${netty.version}version>
dependency>
dependencies>
<build>
<finalName>${project.artifactId}finalName>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
configuration>
plugin>
plugins>
build>
二、netty服务端编写
NettyServer
/**
* netty服务端 .
*
* @author hkb
*/
@Component
public class NettyServer {
/**
* 日志
*/
private Logger log = LoggerFactory.getLogger(getClass());
/**
* 端口号
*/
@Value("${netty.port}")
private int port;
/**
* 启动服务器方法
*
* @param port
*/
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
serverBootstrap.childHandler(new NettyServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
log.info("netty服务启动: [port:" + port + "]");
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error("netty服务启动异常-" + e.getMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
NettyServerInitializer
/**
* 服务端初始化 .
*
* @author hkb
*/
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
/**
* 初始化channel
*/
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new NettyServerHandler());
}
}
NettyServerHandler
/**
* 服务端处理器 .
*
* @author hkb
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 日志
*/
private Logger log = LoggerFactory.getLogger(getClass());
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
StringBuilder sb = null;
Map result = null;
try {
sb = new StringBuilder();
result = JSON.parseObject(msg);
sb.append(result);
sb.append("解析成功");
sb.append("\n");
ctx.writeAndFlush(sb);
} catch (Exception e) {
String errorCode = "-1\n";
ctx.writeAndFlush(errorCode);
log.error("报文解析失败: " + e.getMessage());
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = insocket.getAddress().getHostAddress();
log.info("收到客户端[ip:" + clientIp + "]连接");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
三、配置netty随tomcat启动
/**
* netty服务监听器 .
*
* @author hkb
*/
@WebListener
public class NettyServerListener implements ServletContextListener {
/**
* 注入NettyServer
*/
@Autowired
private NettyServer nettyServer;
@Override
public void contextInitialized(ServletContextEvent sce) {
Thread thread = new Thread(new NettyServerThread());
thread.start();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
/**
* netty服务启动线程 .
*
* @author hkb
*/
private class NettyServerThread implements Runnable {
@Override
public void run() {
nettyServer.run();
}
}
}
四、netty客户端测试
NettyClient
/**
* netty客户端 .
*
* @author hkb
*/
public class NettyClient {
/**
* 主机
*/
private String host;
/**
* 端口号
*/
private int port;
/**
* 构造函数
*
* @param host
* @param port
*/
public NettyClient(String host, int port) {
this.host = host;
this.port = port;
}
/**
* 连接方法
*/
public void connect() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.handler(new NettyClientInitializer());
Channel channel = bootstrap.connect(host, port).sync().channel();
String msg = "{\"name\":\"admin\",\"age\":27}\n";
channel.writeAndFlush(msg);
channel.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
/**
* 测试入口
*
* @param args
*/
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 8088;
NettyClient nettyClient = new NettyClient(host, port);
nettyClient.connect();
}
}
NettyClientInitializer
/**
* 客户端初始化 .
*
* @author hkb
*/
public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
/**
* 初始化channel
*/
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new NettyClientHandler());
}
}
NettyClientHandler
/**
* 客户端处理器 .
*
* @author hkb
*/
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("收到服务端消息: " + msg);
}
}
五、运行结果
服务端
客户端