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初体验的更多相关文章

  1. 蚂蚁 RPC 框架 SOFA-RPC 初体验

    前言 最近蚂蚁金服开源了分布式框架 SOFA,楼主写了一个 demo,体验了一下 SOFA 的功能,SOFA 完全兼容 SpringBoot(当然 Dubbo 也是可以兼容的). 项目地址:Alipa ...

  2. 高性能无锁队列 Disruptor 初体验

    原文地址: haifeiWu和他朋友们的博客 博客地址:www.hchstudio.cn 欢迎转载,转载请注明作者及出处,谢谢! 最近一直在研究队列的一些问题,今天楼主要分享一个高性能的队列 Disr ...

  3. 阿里 RPC 框架 DUBBO 初体验

    最近研究了一下阿里开源的分布式RPC框架dubbo,楼主写了一个 demo,体验了一下dubbo的功能. 快速开始 实际上,dubbo的官方文档已经提供了如何使用这个RPC框架example代码,基于 ...

  4. RPC框架基础概念理解以及使用初体验

    RPC:Remote Procedure Call(远程服务调用) RPC是做什么的 通过RPC框架机器A某个进程可以通过网络调用机器B上的进程方法,就像在本地上调用一样. RPC可以基于HTTP或者 ...

  5. dubbo实战之一:准备和初体验

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  6. .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验

    不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...

  7. Xamarin+Prism开发详解四:简单Mac OS 虚拟机安装方法与Visual Studio for Mac 初体验

    Mac OS 虚拟机安装方法 最近把自己的电脑升级了一下SSD固态硬盘,总算是有容量安装Mac 虚拟机了!经过心碎的安装探索,尝试了国内外的各种安装方法,最后在youtube上找到了一个好方法. 简单 ...

  8. Spring之初体验

                                     Spring之初体验 Spring是一个轻量级的Java Web开发框架,以IoC(Inverse of Control 控制反转)和 ...

  9. Xamarin.iOS开发初体验

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKwAAAA+CAIAAAA5/WfHAAAJrklEQVR4nO2c/VdTRxrH+wfdU84pW0

随机推荐

  1. BBS论坛(三十二)

    32.帖子排序功能完成 (1)front_index.html <ul class="post-group-head"> {% if current_sort==1 % ...

  2. web Components 学习之路

    就目前而言,纯粹的Web Components在兼容性方面还有着较为长远的路,这里做个记录总结,以纪念自己最近关于Web Components的学习道路. 参考教材 JavaScript 标准参考教程 ...

  3. springBoot(12)---整合Swagger2

    Spingboot整合Swagger2 随着互联网技术的发展,一般开发都是前后端分离,那么前端和后端的唯一联系,变成了API接口:API文档变成了前后端开发人员联系的纽带,变得越来越重要,没有API ...

  4. RAC集群数据库连库代码示例(jdbc thin方式,非oci)

    1.RAC集群数据库连库代码示例(jdbc thin方式,非oci):jdbc.driverClassName=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc ...

  5. 可视化面板LogDashboard使用log4net源

    logdashboard现已支持log4net文件源,本示例源码在 https://github.com/liangshiw/LogDashboard/tree/master/samples/UseL ...

  6. C# 如何添加PPT背景(纯色背景、渐变色背景、图片背景)

    我们在创建Powerpoint文档时,系统默认的幻灯片是空白背景的,很多时候我们需要自定义幻灯片背景,以达到美观的文档效果.在下面的示例中将介绍给PowerPoint幻灯片设置背景的方法,主要包含以下 ...

  7. 学JAVA第三天,JAVA第二章《JAVA数据类型》

    ---恢复内容开始--- <JAVA数据类型> 我们一般都用int类型,因为int类行一般的日常生活的数据都能满足了. 当然,想李嘉诚,马云这种有钱人,int类行就不能满足帮他记钱的了,像 ...

  8. 有关mysql实现oracle分析函数功能的方法

    目前公司erp开发有一个脚本需求:对于收款合同审批单和收款合同(n:1),需要获取收款审批单中最新的一条审批记录来更新其对应的收款合同的相关信息. 难点主要在对相同类别的属性进行分组然后组内排序(分组 ...

  9. vue遍历数组和对象的方法以及他们之间的区别

    前言:vue不能直接通过下标的形式来添加数据,vue也不能直接向对象中插值,因为那样即使能插入值,页面也不会重新渲染数据 一,vue遍历数组   1,使用vue数组变异方法 pop() 删除数组最后一 ...

  10. vue2.x 在引用插件的时候,npm run dev跑正常 ,npm run build 报错vue-cli Unexpected token: punc (() [

    这是因为,引用的插件在node_modules里,并不在vue-cli的es6编译范围内,所以语法报错,修改方法: