2.netty的helloworld
来源:互联网 发布:广告过滤软件 编辑:程序博客网 时间:2024/05/29 02:45
一.server
1.server
package netty.helloworld;import java.net.InetSocketAddress;import io.netty.bootstrap.ServerBootstrap;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.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;public class netty_server {public static void main(String [] args){new netty_server().start();}public void start(){//1.引导辅助程序ServerBootstrap boot = new ServerBootstrap();//2.创建EventLoop用于处理Channel的所有请求所有数据逻辑处理EventLoopGroup group = new NioEventLoopGroup();try {boot.group(group);//3.设置Channel类型为Nio类型boot.channel(NioServerSocketChannel.class);//4.设置监听端口boot.localAddress(new InetSocketAddress(9090));//5.每当连接达到时就创建一个Channel实现类(传入一个ChannelInitializer接口)boot.childHandler(new ChannelInitializer<SocketChannel>(){@Overrideprotected void initChannel(SocketChannel channel) throws Exception {//pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务channel.pipeline().addLast("myHandler", new netty_server_handler());}});//6.配置完成,绑定server,通过调用sync同步方法阻塞直到绑定成功,同时返回一个回调ChannelFuture future = boot.bind().sync();System.out.println("启动server :"+ netty_server.class.getName());System.out.println("监听的端口是 :"+ future.channel().localAddress());//7.程序会一直等待直到channel关闭future.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();}}}
2.handler
package netty.helloworld;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandler.Sharable;import io.netty.channel.ChannelHandlerContext;/* * 这个类是我们的具体业务类: * * 1.处理接收到的数据,方法中写处理逻辑 * * 2.注解@Sharable(这个类对象)可以让它在channels间共享 * * 3. * channelRead:拿到接收到的数据 * channelReadComplete:在channelRead之后执行,这里添加监听器关闭channel * * */@Sharablepublic class netty_server_handler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//通过ByteBuf读取收到的客户端消息,打印 ByteBuf result = (ByteBuf) msg; byte[] result1 = new byte[result.readableBytes()]; result.readBytes(result1); String resultStr = new String(result1); System.out.println("Client said:" + resultStr); result.release(); ctx.write(msg);//写回数据}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {//flush掉所有写回的数据//当flush完成后关闭channelctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();//出现异常时关闭channel}}
二.client
1.client
package netty.helloworld;import java.net.InetSocketAddress;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandler;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class netty_client {public static void main(String[] args) throws InterruptedException {new netty_client().start();}public void start() throws InterruptedException{//1.创建EventLoop:一个线程驱动,处理一个channel 所有 IO事件EventLoopGroup group = new NioEventLoopGroup(); try {//2.创建引导Bootstrap b = new Bootstrap();b.group(group);b.channel(NioSocketChannel.class);//设置channel为Nio类型b.remoteAddress(new InetSocketAddress("192.168.31.170", 9090));//服务器ip和port//3.创建handler(客户端处理者)传入一个ChannelInitializer接口b.handler(new ChannelInitializer<SocketChannel>() {public void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast( new netty_client_handler());}});//4.ChannelFuture f = b.connect().sync();f.addListener(new ChannelFutureListener() {public void operationComplete(ChannelFuture future) throws Exception {if(future.isSuccess()){System.out.println("client connected");}else{System.out.println("server attemp failed");future.cause().printStackTrace();}}});//5.f.channel().closeFuture().sync();}catch (Exception e){}finally{group.shutdownGracefully().sync();}}}
2.handler
package netty.helloworld;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class netty_client_handler extends SimpleChannelInboundHandler<ByteBuf >{@Overrideprotected void messageReceived(ChannelHandlerContext arg0, ByteBuf arg1) throws Exception {}@Override//此方法会在连接到服务器后被调用,在这里向服务器发送消息public void channelActive(ChannelHandlerContext ctx) throws Exception { String msg = "Are you ok?"; ByteBuf encoded = ctx.alloc().buffer(4 * msg.length()); encoded.writeBytes(msg.getBytes()); ctx.write(encoded); ctx.flush(); }@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {}}
阅读全文
0 0
- 2.netty的helloworld
- Netty的HelloWorld
- Netty:HelloWorld
- 基于netty的helloworld(打成jar)
- Netty之HelloWorld
- netty——helloworld
- Netty框架的学习经历初级篇---helloworld
- Netty学习(二)-Helloworld Netty
- 3、netty 之HelloWorld(netty学习笔记)
- Netty学习笔记—helloWorld
- Netty学习(三)HelloWorld服务器
- Netty 学习(7)Netty Example http helloworld
- Netty学习之旅(二)(HelloWorld)
- Netty------对于Netty的十一个疑问
- Netty 之 Netty使用Google的ProtoBuf
- Netty学习(八)-Netty的心跳机制
- 【Netty入门】基于Netty的Server / Client
- 【Netty入门】Netty的线程模型
- [深度学习]Contractive Autoencoder
- 棋盘覆盖--分治法
- 真人秀
- 数组操作系列之去除空值与转换汉字
- maven项目配置redis,实现购物车功能
- 2.netty的helloworld
- 动态代理-CGLib动态代理
- 矩阵DP例题
- oracle开机自启配置
- 修改windows控制台的编码格式为utf-8
- 10月小贷严打禁令:互金资金不能用来买房,违规将影响征信
- 2017ACM-ICPC亚洲区域赛西安站热身赛 B. A+B or A-B(模拟)
- 在 WPA2 安全协议存在漏洞的情况下,我们应该如何保护自己?
- Java通过Spring MVC导出批量Excel文件压缩包,并弹出下载框