netty4.0.23 初学的demo
例子共4个文件,用到的jar包有:
netty-all-4.0.23.Final.jar
log4j.jar (apache的)
commons-logging-1.1.1.jar(apache的)
文件 TcpServerHandler
- package test.netty;
- import org.apache.log4j.Logger;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
- private static final Logger logger = Logger.getLogger(TcpServerHandler.class);
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, Object msg)
- throws Exception {
- logger.info("SERVER接收到消息:"+msg);
- ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg);
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx,
- Throwable cause) throws Exception {
- logger.warn("Unexpected exception from downstream.", cause);
- ctx.close();
- }
- }
文件 TcpServer
- package test.netty;
- import org.apache.log4j.Logger;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelPipeline;
- 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.codec.LengthFieldBasedFrameDecoder;
- import io.netty.handler.codec.LengthFieldPrepender;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- import io.netty.util.CharsetUtil;
- public class TcpServer {
- private static final Logger logger = Logger.getLogger(TcpServer.class);
- private static final String IP = "127.0.0.1";
- private static final int PORT = 9999;
- /**用于分配处理业务线程的线程组个数 */
- protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认
- /** 业务出现线程大小*/
- protected static final int BIZTHREADSIZE = 4;
- /*
- * NioEventLoopGroup实际上就是个线程池,
- * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
- * 每一个NioEventLoop负责处理m个Channel,
- * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
- */
- private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
- private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
- protected static void run() throws Exception {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup);
- b.channel(NioServerSocketChannel.class);
- b.childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ChannelPipeline pipeline = ch.pipeline();
- pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
- pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
- pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
- pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
- pipeline.addLast(new TcpServerHandler());
- }
- });
- b.bind(IP, PORT).sync();
- logger.info("TCP服务器已启动");
- }
- protected static void shutdown() {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- public static void main(String[] args) throws Exception {
- logger.info("开始启动TCP服务器...");
- TcpServer.run();
- // TcpServer.shutdown();
- }
- }
文件 TcpClientHandler
- package test.netty;
- import org.apache.log4j.Logger;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {
- private static final Logger logger = Logger.getLogger(TcpClientHandler.class);
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, Object msg)
- throws Exception {
- //messageReceived方法,名称很别扭,像是一个内部方法.
- logger.info("client接收到服务器返回的消息:"+msg);
- }
- }
文件 TcpClient
- package test.netty;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.Channel;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.ChannelPipeline;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.nio.NioSocketChannel;
- import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
- import io.netty.handler.codec.LengthFieldPrepender;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- import io.netty.util.CharsetUtil;
- import org.apache.log4j.Logger;
- public class TcpClient {
- private static final Logger logger = Logger.getLogger(TcpClient.class);
- public static String HOST = "127.0.0.1";
- public static int PORT = 9999;
- public static Bootstrap bootstrap = getBootstrap();
- public static Channel channel = getChannel(HOST,PORT);
- /**
- * 初始化Bootstrap
- * @return
- */
- public static final Bootstrap getBootstrap(){
- EventLoopGroup group = new NioEventLoopGroup();
- Bootstrap b = new Bootstrap();
- b.group(group).channel(NioSocketChannel.class);
- b.handler(new ChannelInitializer<Channel>() {
- @Override
- protected void initChannel(Channel ch) throws Exception {
- ChannelPipeline pipeline = ch.pipeline();
- pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
- pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
- pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
- pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
- pipeline.addLast("handler", new TcpClientHandler());
- }
- });
- b.option(ChannelOption.SO_KEEPALIVE, true);
- return b;
- }
- public static final Channel getChannel(String host,int port){
- Channel channel = null;
- try {
- channel = bootstrap.connect(host, port).sync().channel();
- } catch (Exception e) {
- logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", host,port),e);
- return null;
- }
- return channel;
- }
- public static void sendMsg(String msg) throws Exception {
- if(channel!=null){
- channel.writeAndFlush(msg).sync();
- }else{
- logger.warn("消息发送失败,连接尚未建立!");
- }
- }
- public static void main(String[] args) throws Exception {
- try {
- long t0 = System.nanoTime();
- for (int i = 0; i < 100000; i++) {
- TcpClient.sendMsg(i+"你好1");
- }
- long t1 = System.nanoTime();
- System.out.println((t1-t0)/1000000.0);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
相关推荐
netty最新发布jar包,网上很多资料都不能用,这个肯定可以用,我自己已经用了,有问题可以咨询我。
netty通信所需jar包,最新jar包。个人使用的nettyjar包。
springboot整合netty的demo,下载后解压即可使用,包含server和client端
简易版netty websocket通讯demo 聊天
官方自带的netty5.0案例,非常强大,学习netty必备!
这是一个基于高并发网络框架-Netty框架的demo项目,旨在展示Netty服务端与客户端的基础使用方式,并深入探讨了自定义编解码器以及心跳机制的实现。...无论是Netty初学者还是有一定基础的开发者,都能从中获益匪浅。
作为一个学Java的,如果没有研究过Netty,那么你对Java语言的使用和理解仅仅停留在表面水平。 如果你想知道Nginx是怎么写出来的,如果你想知道Tomcat和Jetty是如何实现的,如果你也想实现一个简单的Redis服务器,那...
netty代码demo
Netty-4.0.23 开发文档(英文原版开发手册)
netty通信的基本案例,类似QQ的效果
这是更具netty的一个demo自己再修改一下 有问题可以联系我
websocket,java做pc端数据推送必备,2021年11月最新版本jar包,含nettyio-demo官方demo及nettyio1.7.19 jar包及所有依赖15个jar包
netty及时通讯通讯DEMO!!!!!!!!!!!!!!!
在android端使用netty的demo,详情可以看我的博客http://blog.csdn.net/jan_s
netty4.0.26 英文版 api chm,, 英文版哦,无能力翻译~~
基于netty的nio使用demo源码
netty案例,netty4.1基础入门篇十一《netty udp通信方式案例Demo》源码 https://mp.weixin.qq.com/s?__biz=MzIxMDAwMDAxMw==&mid=2650724927&idx=1&sn=a16bc8e98d6a27816da0896adcc83778&scene=19#wechat_redirect
采用队列等待实现netty客户端同步调用,zookeeper管理分布式服务端。
protobuf-netty-Demo
一个Netty的使用demo,可以帮助你更好的了解Netty的使用,对netty有更加清晰的了解。下载即可运行