JAVA(5)-NETTY-server
netty是把nio封装好的好用的库。
不得不说ByteBuf非常好用。
两点:1.ByteBuf读、写分离,不是一个指针。
2.它可以直接访问系统地址,速度超级的快。一般数据流程:网络->系统->用户应用堆栈内存,ByteBuf可以访问系统内核级的,而不只是用户应用层的堆栈。
1.添加jar包
2.SERVER
2.1main()
2.2处理管道的
2.3处理数据的
3.CLIENT
4.结果
1.添加jar包
2.idea 下 Project structure->modules->dependencies->library->from maven
一般选的是4版本的。5版本被废,6版本还没出来,4版本最稳定。
原理与过程参看其它文档吧。我这直接上可以运行的源码。
2.server
2.1main()
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//1.两个线程组,一个负责接客,一个负责服务
//1.1负责 接客
EventLoopGroup bossGroup=new NioEventLoopGroup(2);
//1.2负责 服务
EventLoopGroup workerGroup=new NioEventLoopGroup(4);
//1.3Server 启动辅助类
ServerBootstrap b =new ServerBootstrap();
b.group(bossGroup,workerGroup);
//2.设置属性:异步全双工
b.channel(NioServerSocketChannel.class);
//3.管道 socketChannel 通道 此通道是连接好的。
b.childHandler(new MyChildInitializer());
b.bind(8888).sync();
}
}
2.2用来管通道的myChildInitializer() ChannelInitializer<SocketChannel>
// 初始化管道
class MyChildInitializer extends ChannelInitializer<SocketChannel>
{
@Override
public void initChannel(SocketChannel socketChannel) throws Exception {
//System.out.println("a client connected!");
socketChannel.pipeline().addLast(new MyChildHandler());//管道上可以有多个处理器
}
}
2.3 用来处理数据的myChildHandler() ChannelInboundHandlerAdapter
注意:1.连上来的处理器
2.一般重写的有两个:读取和异常处理
class MyChildHandler extends ChannelInboundHandlerAdapter
{
//1.读取
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//1.读出
ByteBuf buf=(ByteBuf)msg;
//输出编码格式
// System.out.println(buf.toString(ChartsetUtil.UTF_8));
System.out.println("server rec:" +buf.toString());
//2.写回去
ctx.writeAndFlush(msg);
// buf.release();
// super.channelRead(ctx, msg);
}
//2.异常处理
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
3.Client
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 8888);
//1.写出去
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("client:send---clientsendMsg");
bw.newLine(); //必须加上
bw.flush();
//2.读到
BufferedReader reader=new BufferedReader(new InputStreamReader(s.getInputStream()));
String str=reader.readLine();
System.out.println("client:rec"+str);
bw.close();
}
}
4.结果
启动服务器,再启动客户端,你也可以看到。

浙公网安备 33010602011771号