netty 4.1.31
服务端代码
import com.crane.mudal.project.socket.WebsocketServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.boot.ApplicationArguments;
import java.util.concurrent.TimeUnit;
public class NettyServer {
private static final int port = 3000;
public void run() throws Exception{
//NioEventLoopGroup是用来处理IO操作的多线程事件循环器
EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用来接收进来的连接
EventLoopGroup workerGroup = new NioEventLoopGroup();// 用来处理已经被接收的连接
try{
ServerBootstrap server =new ServerBootstrap();//是一个启动NIO服务的辅助启动类
server.group(bossGroup,workerGroup )
.channel(NioServerSocketChannel.class) // 这里告诉Channel如何接收新的连接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 自定义处理类
ch.pipeline().addLast(new IdleStateHandler(31,0,0, TimeUnit.SECONDS));
ch.pipeline().addLast(new IdleStateTrigger());
ch.pipeline().addLast(new NettyServerHandler());
}
});
server.option(ChannelOption.SO_BACKLOG,1024);
server.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = server.bind(port);// 绑定端口,开始接收进来的连接
System.out.println("服务端启动成功...");
// 监听服务器关闭监听
f.channel().closeFuture();
}finally {
// bossGroup.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程
// workerGroup.shutdownGracefully();
}
// 服务器绑定端口监听
}
数据处理部分
import com.alibaba.fastjson.JSONArray;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.Date;
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//收到数据时调用
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf in = (ByteBuf) msg;
int readableBytes = in.readableBytes();
byte[] bytes = new byte[readableBytes];
in.readBytes(bytes);
} finally {
// 抛弃收到的数据
ReferenceCountUtil.release(msg);
}
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
logger.error("connection断开:" + ctx.channel().remoteAddress());
}
/*
* 建立连接时,返回消息
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.info("连接的客户端地址:" + ctx.channel().remoteAddress());
ctx.writeAndFlush("client" + InetAddress.getLocalHost().getHostName() + "success connected! \n");
super.channelActive(ctx);
}
}
超时处理
package com.crane.mudal.project.netty;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
@ChannelHandler.Sharable
public class IdleStateTrigger extends ChannelInboundHandlerAdapter {
private Log logger = LogFactory.getLog(IdleStateTrigger.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state = ((IdleStateEvent) evt).state();
ctx.channel().close();
}
} else {
super.userEventTriggered(ctx, evt);
}
}
}
客户端
import com.crane.mudal.project.utils.Crc;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class HeartBeatClient {
int port = 3000;
Channel channel;
public static void run() throws Exception {
heartBeatClient.start();
}
public void start() {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
.handler(new HeartBeatClientInitializer());
connect(bootstrap, port);
String text = "www.usr.cn";
while (channel.isActive()) {
sendMsg(text);
}
} catch (Exception e) {
// do something
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public void connect(Bootstrap bootstrap, int port) throws Exception {
channel = bootstrap.connect("localhost", 3000).sync().channel();
}
public void sendMsg(String text) throws Exception {
int num = 30;
Thread.sleep(num * 1000);
channel.writeAndFlush(text);
}
static class HeartBeatClientInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast(new HeartBeatClientHandler());
}
}
static class HeartBeatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(" client received :" + msg);
if (msg != null && msg.equals("you are out")) {
System.out.println(" server closed connection , so client will close too");
ctx.channel().closeFuture();
}
}
}
@Scheduled(initialDelay = 3000,fixedRate = 36000000)
public void Tasks() throws InterruptedException {
}
}
基本上就是这些代码,netty4用起来还不错没有明显的坑。只有一点值得注意在启动服务端的时候把sync()去掉后,不把
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
注释掉。会关闭服务器
netty4向client发送数据时,默认编码为字节,如果encode和decode定义为new StringEncoder()这类则发送字符串。
默认时要发送ByteBuf,通过ByteBuf buf = Unpooled.wrappedBuffer(msgByte);将byte[]转为ByteBuf,然后发送。