Netty初体验
package netty_starter; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; /**
* @auther guozg
*/
public class DiscardServer { private int port; public DiscardServer(int port) {
this.port = port;
} public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler())
.addLast(new OpenHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6) // Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
} public static void main(String[] args) throws InterruptedException {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8088;
}
new DiscardServer(port).run();
}
}
package netty_starter; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import study01.ChannelList; /**
* @auther guozg
*/
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // (2)
// super.channelRead(ctx, msg);
// ((ByteBuf) msg).release(); // (3)
ByteBuf in = (ByteBuf) msg;
String message = in.toString(CharsetUtil.UTF_8);
System.out.println(message);
sendMessage(Unpooled.copiedBuffer(message,CharsetUtil.UTF_8).retain(ChannelList.channels.size()-1),ctx.channel());
// try {
// while (in.isReadable()) {
// char s = in.getChar(0);
// System.out.print((char) in.readByte());
// System.out.flush();
// }
// } finally {
// ReferenceCountUtil.release(msg);
// }
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // (5)
// super.exceptionCaught(ctx, cause);
cause.printStackTrace();
ctx.close();
} public void sendMessage(Object msg,Channel channel){ for (Channel c:ChannelList.channels){
if(channel != c) {
c.writeAndFlush(msg);
}
} } }
package netty_starter; import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import study01.ChannelList; public class OpenHandler extends ChannelInboundHandlerAdapter { @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ChannelList.channels.add(ctx.channel());
sendMessage(Unpooled.copiedBuffer("New client in!\n",CharsetUtil.UTF_8).retain(ChannelList.channels.size()));//retain设置读取次数
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
ChannelList.channels.remove(ctx.channel());
ctx.close();
sendMessage(Unpooled.copiedBuffer("One client out!\n",CharsetUtil.UTF_8).retain(ChannelList.channels.size()));
} public void sendMessage(Object msg){ for (Channel c:ChannelList.channels){
c.writeAndFlush(msg);
} }
}
然后启动cmd,输入telnet 127.0.0.1 8088.即可链接服务,并有返回值。可同时启动多个Telnet,实现群发消息。
Netty初体验的更多相关文章
- 蚂蚁 RPC 框架 SOFA-RPC 初体验
前言 最近蚂蚁金服开源了分布式框架 SOFA,楼主写了一个 demo,体验了一下 SOFA 的功能,SOFA 完全兼容 SpringBoot(当然 Dubbo 也是可以兼容的). 项目地址:Alipa ...
- 高性能无锁队列 Disruptor 初体验
原文地址: haifeiWu和他朋友们的博客 博客地址:www.hchstudio.cn 欢迎转载,转载请注明作者及出处,谢谢! 最近一直在研究队列的一些问题,今天楼主要分享一个高性能的队列 Disr ...
- 阿里 RPC 框架 DUBBO 初体验
最近研究了一下阿里开源的分布式RPC框架dubbo,楼主写了一个 demo,体验了一下dubbo的功能. 快速开始 实际上,dubbo的官方文档已经提供了如何使用这个RPC框架example代码,基于 ...
- RPC框架基础概念理解以及使用初体验
RPC:Remote Procedure Call(远程服务调用) RPC是做什么的 通过RPC框架机器A某个进程可以通过网络调用机器B上的进程方法,就像在本地上调用一样. RPC可以基于HTTP或者 ...
- dubbo实战之一:准备和初体验
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...
- Xamarin+Prism开发详解四:简单Mac OS 虚拟机安装方法与Visual Studio for Mac 初体验
Mac OS 虚拟机安装方法 最近把自己的电脑升级了一下SSD固态硬盘,总算是有容量安装Mac 虚拟机了!经过心碎的安装探索,尝试了国内外的各种安装方法,最后在youtube上找到了一个好方法. 简单 ...
- Spring之初体验
Spring之初体验 Spring是一个轻量级的Java Web开发框架,以IoC(Inverse of Control 控制反转)和 ...
- Xamarin.iOS开发初体验
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKwAAAA+CAIAAAA5/WfHAAAJrklEQVR4nO2c/VdTRxrH+wfdU84pW0
随机推荐
- Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录
基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...
- IntelliJ IDEA中创建Web聚合项目(Maven多模块项目)
Eclipse用多了,IntelliJ中创建Maven聚合项目可能有小伙伴还不太熟悉,我们今天就来看看. IntelliJ中创建普通的Java聚合项目相对来说比较容易,不会涉及到web操作,涉及到we ...
- [Leetcode]669 Trim a Binary Search Tree
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that a ...
- Django中的templates(你的HTML页面放哪里)
本文回答Django里面的HTML文件应该怎么放,以及Django是如何查找模板文件的. 到目前为止我们没有使用HTML页面,在之前的说明中所有内容都是写死在程序里的,如果你想改变内容就要修改代码.但 ...
- navicat连接mysql出现Client does not support authentication protocol requested by server解决方案
USE mysql; '; FLUSH PRIVILEGES; root是用户名 localhost是ip地址127.0.0.1都是特指本机,%表示任何IP都可访问 mysql_native_pass ...
- 【ASP.NET Core快速入门】(十三)Individual authentication 模板、EF Core Migration
Individual authentication 模板 我们首先用VSCode新建一个mvc的网站,这个网站创立的时候回自动为我们创建Identuty Core以及EF Core的代码示例,我们可以 ...
- [十五]java.math包简介,RoundingMode与MathContext
java.math包提供了java中的数学类 包括基本的浮点库.复杂运算以及任意精度的数据运算 '可以看得到,主要包括三个类一个枚举 BigDecimal和BigInteger接下来会详细介绍 先 ...
- gulp插件gulp-nunjucks-render的使用及gulp4的简单了解
之前写过一篇gulp的使用文章一篇迟到的gulp文章,代码合并压缩,less编译 最近有在用gulp,使用到一个gulp-nunjucks-render插件,感觉挺方便的 gulp-nunjucks- ...
- mpvue微信小程序多列选择器用法:实现省份城市选择
前言 微信小程序默认给我们提供了一个省市区的picker选择器,只需将mode设置为region即可 <picker mode="region" bindchange=&qu ...
- 第7章 贡献 - Identity Server 4 中文文档(v1.0.0)
我们对社区贡献非常开放,但您应该遵循一些指导原则,以便我们可以毫不费力地处理这个问题. 7.1 如何贡献? 最简单的方法是打开一个问题并开始讨论.然后我们可以决定是否以及如何实现功能或更改.如果您应提 ...