maven
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
netty启动类
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NioServer {
public static void main(String[] args) {
new NioServer().start();
}
private void start() {
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(8888)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
//这里添加处理器
.addLast(new MyNioServerHandler());
}
});
ChannelFuture future = bootstrap.bind().sync();
System.out.println("=======netty启动");
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
所有的启动类基本上都一致,复制即可.
需要注意的是,本类启动了8888端口作为netty的接收端口.
其次,在addLast(new MyNioServerHandler());这里,添加了一个处理器叫做MyNioServerHandler,其实pipeline这里是处理器链,仍然可以添加其他处理器.
MyNioServerHandler是自定义的处理器,我们看一个简单的例子
简单处理器
import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class MyNioServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg;
String msgStr = bb.toString(Charset.forName("UTF-8")); 这个相当于转成字符串
System.out.println("read " + msgStr);//打印发来的东西
ctx.writeAndFlush(msg);//把发来的消息再返回去
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("========异常");
super.exceptionCaught(ctx, cause);
}
}
网络传输发来的都是字节数组,但是netty做了封装,默认发来的都是ByteBuf
接下来运行netty启动类的main方法,就启动了一个服务器.
然后用二进制发送接收工具发送即可,就会接到和发送相同的消息.