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
随机推荐
- ECMAScript 6 学习(一)generator函数
1.ES2017标准引入async函数,那么async函数到底是个什么函数呢? async 是一个generator函数的语法糖. 2.那么generator函数到底是什么函数ne? generato ...
- SignalR学习笔记(二)高并发应用
虽然SignalR借助Websocket提供了很强大的实时通讯能力,但是在有些实时通讯非常频繁的场景之下,如果使用不当,还是会导致服务器,甚至客户端浏览器崩溃. 以下是一个实时拖拽方块项目的优化过程 ...
- 前端笔记之JavaScript(十)深入JavaScript节点&DOM&事件
一.DOM JavaScript语言核心.变量的定义.变量的类型.运算符.表达式.函数.if语句.for循环.算法等等.这些东西都属于语言核心,下次继续学习语言核心就是面向对象了.JavaScript ...
- Python进阶:切片的误区与高级用法
2018-12-31 更新声明:切片系列文章本是分三篇写成,现已合并成一篇.合并后,修正了一些严重的错误(如自定义序列切片的部分),还对行文结构与章节衔接做了大量改动.原系列的单篇就不删除了,毕竟也是 ...
- 【ASP.NET Core快速入门】(十)Cookie-based认证实现
准备工作 新建MVC项目,然后用VSCode打开 dotnet new mvc --name MvcCookieAuthSample 在Controllers文件夹下新建AdminController ...
- leetcode — word-ladder
import java.util.*; /** * Source : https://oj.leetcode.com/problems/word-ladder/ * * * Given two wor ...
- javaWeb项目中的路径格式 请求url地址 客户端路径 服务端路径 url-pattern 路径 获取资源路径 地址 url
javaweb项目中有很多场景的路径客户端的POST/GET请求,服务器的请求转发,资源获取需要设置路径等这些路径表达的含义都有不同,所以想要更好的书写规范有用的路径代码 需要对路径有一个清晰地认知 ...
- springmvc 项目完整示例01 需求与数据库表设计 简单的springmvc应用实例 web项目
一个简单的用户登录系统 用户有账号密码,登录ip,登录时间 打开登录页面,输入用户名密码 登录日志,可以记录登陆的时间,登陆的ip 成功登陆了的话,就更新用户的最后登入时间和ip,同时记录一条登录记录 ...
- BlockingQueue 阻塞队列实现异步事件
转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10411444.html 前言 本文通过一个简单的例子,来展现如何使用阻塞队列(BlockingQueue)来 ...
- DataTable转换成List集合,传递到HTML页面
public string GetPwd(string str) { var dt= bll.Gets(str); List<string> list = new List<stri ...