首页 > 编程知识 正文

netty channelhandler,netty教程菜鸟

时间:2023-05-04 12:24:40 阅读:23868 作者:3719

1 .字符串传输1. netty开发基本流程的基本流程

-详细进程的红色位置是客户端和服务端的不同位置

驼峰命名法创建的项目名称

内部jar包名称均为小写

创建类

-创建类

2 .分别实现客户端和服务器端2.1实现客户端(1)添加Sharable注释,使线程安全

客户端的消息接收和异常处理

package com.xc.helloworld; import io.netty.buffer.ByteBuf; import io.net ty.channel.channel handler; import io.net ty.channel.channelhandlercontext; import io.net ty.channel.simplechannelinboundhandler; import java.nio.ByteBuffer; /** * @Author繁荣的灯泡* @ date 2008/08/1120:42 * @ description; 通用handler,处理I/O时间*/@ChannelHandler.Sharable//为了线程安全,使用publicclasshandlerclienthelloextendssimplechannelinboundhandlerbytebuf { @ overrideprotectedvoidchannelread0(频道otectedvoidchannelre handler context,bytebufbytebuf (throws exception (/* * * @ author繁荣灯泡(@ date 2008/08/1120:42 ) 处理接收到的消息*///sout System.out.println (接收到的消息); 输入//ex,添加以下异常处理@ overridepublicvoidexceptioncaught (channelhandlercontextctx,Throwable cause ) throwsexception ) ctx.close (; }

创建客户端启动类

package com.xc.helloworld; import io.net ty.bootstrap.bootstrap; import io.netty.buffer.Unpooled; import io.net ty.channel.channel future; import io.net ty.channel.channel initializer; import io.net ty.channel.event loop; import io.net ty.channel.eventloopgroup; import io.net ty.channel.epoll.epolleventloopgroup; import io.net ty.channel.socket.socket channel; import io.net ty.channel.socket.nio.niosocketchannel; import io.net ty.util.charset util; import Java.net.inetsocketaddress; import java.nio.charset.Charset; /** * @Author繁荣的灯泡* @ date 2008/08/1120:42 * @ description; 客户端启动类*/publicclassappclienthello { privatefinalstringhost; 私有财务输入端口; 如果右键单击generater并选择创建构造函数//或alt insert版本//实例化类,请传递这两个参数,并使用publicappclienthello (字符串主机,) this.port=port; } public void run () throwsexception )/io线程池/** * @Author繁荣的灯泡* @ date 2008/08/1120:42 * @ description; 如何设置适当的参数并将其链接到远程*/eventloopgroupgroup=newepolleventloopgroup (); //IO线程池//CTRL ALT T快速输入try { Bootstrap bs=new Bootstrap (); //客户端辅助启动类bs.group(group ).channel ) niosocketchannel.class )//实例化一个channel.remoteaddress (newinetsocketaddress ) ) hannel.remote address ) )的port ().handler ((newchannner 进行通道初始化配置的{ @ overrideprotectedvoidinitchannel ) ) socketchannelsocket throws exception {//内部配置handler //pipeline管道, 添加//可视为处理程序容器socket channel.pipeline (.add last ) newHandlerclienthello ) )//配置完成//utf8 future.channel (.writeand flush ) unpooled.copiedbuffer )、CharsetUtil.UTF_8) )的形式向服务器发送消息channel知道连接已断开并正在工作) ) future.channel ) ).sync ); } finally { //最后释放资源,释放线程池,然后完全关闭,防止内存泄漏//线程池group.shutdownGracefully ().sync ); } publicstaticvoidmain (字符串[ ] args ) throwsexception ) newappclienthello('127.0.0.1 ',1357 ).run ); }

3.netty的关键知识点

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。