nio之netty5应用
1、netty5和netty4的区别不是很大,但是与netty3差别还是有的。这里不介绍netty4,因为和netty5的方式都差不多。netty5的复杂性相对于netty3要多很多了。基本上架构都被重构了。所以这里主要是介绍一些属性和用法。
2、核心的变化主要有:
- 移动设备变成更加强大
- 通过Ice Cream Sandwich解决了在ADK中最著名的与NIO和SSLEngine相关的问题,且
- 用户显然想要重用他们应用中的的编解码和处理器代码。
EmbeddedChannel ch = ...; // BEFORE:
FullHttpRequest req = (FullHttpRequest) ch.readInbound(); // AFTER:
FullHttpRequest req = ch.readInbound();
3、这里写了一个简单的实现过程,来区分netty5和netty3的写法
1)服务类和处理类
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; public class Server { public static void main(String[] args) {
//服务类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//声明两个线程池
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup(); try {
//设置线程组
serverBootstrap.group(boss,work);
//设置服务socket工厂
serverBootstrap.channel(NioServerSocketChannel.class);
//设置管道
serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new StringEncoder());
channel.pipeline().addLast(new ServerHandler());
}
});
//设置服务器连接数
serverBootstrap.option(ChannelOption.SO_BACKLOG,2048);
//设置tcp延迟状态
serverBootstrap.option(ChannelOption.TCP_NODELAY,true);
//设置激活状态,2小时清除
serverBootstrap.option(ChannelOption.SO_KEEPALIVE,true);
//监听端口
ChannelFuture channelFuture = serverBootstrap.bind(9000);
//等待服务器关闭
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭线程池
boss.shutdownGracefully();
work.shutdownGracefully();
} } }
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; public class ServerHandler extends SimpleChannelInboundHandler<String> { //接收消息并处理
protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
channelHandlerContext.writeAndFlush("hello client");
}
}
2)客户端和处理类
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import java.net.InetSocketAddress;
import java.util.Scanner; //单个客户端
public class Client { public static void main(String[] args) { //服务类
Bootstrap bootstrap = new Bootstrap();
//线程池
EventLoopGroup client = new NioEventLoopGroup(); try {
//设置线程组
bootstrap.group(client);
//设置socket工厂
bootstrap.channel(NioSocketChannel.class);
//设置管道处理
bootstrap.handler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringEncoder());
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new ClientHandler());
}
});
//连接服务器
ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 9000));
//输入信息测试
Scanner scanner = new Scanner(System.in);
while (true) {
String msg = scanner.nextLine();
channelFuture.channel().writeAndFlush(msg);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭线程池
client.shutdownGracefully();
}
}
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; public class ClientHandler extends SimpleChannelInboundHandler<String>{ //接收消息
protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
}
}
3)多个客户端
import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger; //多个客户端连接
public class MClient { //服务类
private Bootstrap bootstrap = new Bootstrap();
//因为线程组里面是线程安全的,所以这里采用数组的形式
private List<Channel> channels = new ArrayList<Channel>();
//原子类,用于计数
private AtomicInteger atomicInteger = new AtomicInteger();
//初始化操作
public void init(int count) {
//声明线程池
EventLoopGroup client = new NioEventLoopGroup();
//设置线程组
bootstrap.group(client);
//设置socket工厂
bootstrap.channel(NioSocketChannel.class);
//设置管道
bootstrap.handler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringEncoder());
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new ClientHandler());
}
});
//初始化连接
for (int i = 0; i < count; i++) {
ChannelFuture channelFuture = bootstrap.connect("10.0.20.154", 9000);
channels.add(channelFuture.channel());
}
} //获取下一个channel
public Channel nextChannel() {
return this.getChannel(0);
} private Channel getChannel(int n) {
//平均获取其中的channel
Channel channel = channels.get(Math.abs(atomicInteger.getAndIncrement() % channels.size()));
//判断是否连接
if (!channel.isActive()) {
//如果没有连接,选择激活替换
channels.set(channels.indexOf(channel), bootstrap.connect("10.0.20.154", 9000).channel());
//超出总长度,直接抛异常
if (n>=channels.size()) {
throw new RuntimeException("no use channel");
}
//递归,目的是获取下一个,直到数组没有channel
return getChannel(n+1);
}
return channel;
} public static void main(String[] args) {
MClient mClient = new MClient();
mClient.init(5);
Scanner scanner = new Scanner(System.in);
while (true) {
try {
String msg = scanner.nextLine();
mClient.nextChannel().writeAndFlush(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
nio之netty5应用的更多相关文章
- Netty、NIO、多线程
一:Netty.NIO.多线程? 时隔很久终于又更新了!之前一直迟迟未动也是因为积累不够,后面比较难下手.过年期间@李林锋hw发布了一个Netty5.0架构剖析和源码解读,看完也是收获不少.前面的文章 ...
- 【转】Netty那点事(四)Netty与Reactor模式
[原文]https://github.com/code4craft/netty-learning/blob/master/posts/ch4-reactor.md 一:Netty.NIO.多线程? 时 ...
- android netty5.0 编译时 java.lang.NoClassDefFoundError: io.netty.channel.nio.NioEventLoopGroup
android netty5.0 编译时 java.lang.NoClassDefFoundError: io.netty.channel.nio.NioEventLoopGroup 复制netty包 ...
- Netty5序章之BIO NIO AIO演变
Netty5序章之BIO NIO AIO演变 Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能.高可靠的网络服务器和客户端程序.Netty简化了网络程序的开发,是很多框架和公司都在使 ...
- 【原创】NIO框架入门(四):Android与MINA2、Netty4的跨平台UDP双向通信实战
概述 本文演示的是一个Android客户端程序,通过UDP协议与两个典型的NIO框架服务端,实现跨平台双向通信的完整Demo. 当前由于NIO框架的流行,使得开发大并发.高性能的互联网服务端成为可能. ...
- 【原创】NIO框架入门(三):iOS与MINA2、Netty4的跨平台UDP双向通信实战
前言 本文将演示一个iOS客户端程序,通过UDP协议与两个典型的NIO框架服务端,实现跨平台双向通信的完整Demo.服务端将分别用MINA2和Netty4进行实现,而通信时服务端你只需选其一就行了.同 ...
- 【原创】NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示
前言 NIO框架的流行,使得开发大并发.高性能的互联网服务端成为可能.这其中最流行的无非就是MINA和Netty了,MINA目前的主要版本是MINA2.而Netty的主要版本是Netty3和Netty ...
- 【原创】NIO框架入门(一):服务端基于Netty4的UDP双向通信Demo演示
申明:本文由作者基于日常实践整理,希望对初次接触MINA.Netty的人有所启发.如需与作者交流,见文签名,互相学习. 学习交流 更多学习资料:点此进入 推荐 移动端即时通讯交流: 215891622 ...
- Netty5 + WebSocket 练习
1. 了解WebSocket知识 略2. websocket实现系统简单反馈时间 WebSocketServerHandler.java package com.jieli.nettytest.web ...
随机推荐
- codeforces 814E An unavoidable detour for home
题目链接 正解:$dp$. 感觉这道题就是中国象棋的加强版..我们要发现一些性质. 首先就是这个图肯定是一个按照$bfs$序分层的图,且每个点只往自己上面那一层连了一条边,每个点不可能向自己的上面超过 ...
- BZOJ5301:[CQOI2018]异或序列(莫队)
Description 已知一个长度为 n 的整数数列 a[1],a[2],…,a[n] ,给定查询参数 l.r ,问在 [l,r] 区间内,有多少连续子 序列满足异或和等于 k . 也就是说,对于所 ...
- Selenium应用代码(常见封装的方法一)
常见封装的方法:输入.点击.判断元素是否存在.根据句柄切换窗口.根据title切换窗口.滚动窗口.截图 import java.awt.Rectangle;import java.awt.image. ...
- LSOF 安装与使用(功能强大)
Linux上安装: tar zxvf lsof_4.76.tar.gz cd lsof_4.76 ls 00.README.FIRST_4.76 lsof_4.76_src.tar.gz ...
- Comparable 接口的使用
//学生类 package test; public class Student implements Comparable<Student>{ private int age; priv ...
- Collections.synchronizedList线程安全性陷阱
摘要: 详细的解析:Collections.synchronizedList 1 :关注要点,为什么在有synchroniezed方法的同时会出现 Collections.synchronizedLi ...
- 使用cmd命令创建vue(ivieiw)项目
条件,安装好nodejs 第一步:先使用 vue create 命令创建一个项目,等待创建完成. 1.切换目录 2.创建项目 vue create [项目名称] 第二步:切换到项目中. 第三步:使用 ...
- [转]表单提交:button input submit 的区别
博客转自于 http://harttle.com/2015/08/03/form-submit.html ,同时自己做了稍微改动 最近项目代码中的表单提交的方式已经百花齐放了,现在用这篇文章来整 ...
- 能成为一名合格的Java架构师
原文地址:http://www.dalbll.com/Group/Topic/ArchitecturedDesign/4943 俗话说“没有见过好程序,怎么可能写出好程序”,同样,也可以说“不了解架构 ...
- 2017年终总结&展望2018年
转眼就要挥别2017年了,也看到好多人都在叹时间过得好快.对啊,在我的印象中时间过得慢的时期恐怕只有中小学期间了,转眼研究生阶段已经过了一半.如今这个阶段,很多时候忙任务和学东西好不容易觉得自己摸到点 ...