Netty是一个Java开源框架,用于传输数据。由server和client组成,封装了Java nio,支持TCP, UDP等协议。这里写了一Demo

EchoClientHandler.java
package chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil; @ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
} protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
System.out.println(msg.toString());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Client received:" + msg.toString()); }
}
EchoServer.java
package chapter1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit; public class EchoServer {
private int port = 1234; public EchoServer(int port) {
this.port = port;
} public static void main(String[] args) throws Exception{
int port = 1234;
EchoServer echoServer = new EchoServer(port);
schedulTask();
echoServer.start(); } public void start() throws Exception{
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture channelFuture = b.bind().sync();
System.out.println("sync test1");
channelFuture.channel().closeFuture().sync();
System.out.println("sync test2"); } catch (Exception e){ }finally {
group.shutdownGracefully().sync();
System.out.println("sync test3");
}
} public static void schedulTask(){
System.out.println("before test");
Channel ch = new EmbeddedChannel();
ch.eventLoop().scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("test");
}
}, 0, 5, TimeUnit.SECONDS);
}
}
EchoClientHandler.java
package chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil; @ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
} protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
System.out.println(msg.toString());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Client received:" + msg.toString()); }
}
EchoClient.java
package chapter1;

import io.netty.bootstrap.Bootstrap;
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.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; public class EchoClient {
private String host;
private int port; public EchoClient(String host, int port) {
this.host = host;
this.port = port;
} public static void main(String[] args) throws Exception {
int port = 1234;
String host = "127.0.0.1";
EchoClient echoClient = new EchoClient(host, port);
echoClient.start();
} public void start() throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync(); }catch (Exception e){
e.printStackTrace();
}finally {
group.shutdownGracefully().sync();
}
}
}

netty如何实现各种回调,怎么发送、接收消息,还要看下源码

netty笔记(一)--Demo的更多相关文章

  1. Kubernetes 笔记 02 demo 初体验

    本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复「1024」即可领取,欢迎大家关注,二维码文末可以扫. 从前面的文章我 ...

  2. Netty心跳简单Demo

    前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...

  3. mybatis笔记<一> Demo

    mybatis作为一个orm互联网公司基本都在用,今天写个笔记.记录一下mybatis使用 参考官网:http://www.mybatis.org/mybatis-3/getting-started. ...

  4. 【Microsoft Azure学习之旅】消息服务Service Bus的学习笔记及Demo示例

    今年项目组做的是Cloud产品,有幸接触到了云计算的知识,也了解并使用了当今流行的云计算平台Amazon AWS与Microsoft Azure.我们的产品最初只部署在AWS平台上,现在产品决定同时支 ...

  5. 【Netty整理01-快速入门】Netty简单使用Demo(已验证)

    多处摘抄或手打,为了十积分厚着脸皮标为原创,惭愧惭愧~本篇文章用于快速入门搭建一个简单的netty 应用,如想稍微深入系统的了解,请参照本人下一篇博客,链接: 参考地址: 官方文档:http://ne ...

  6. 如鹏网仿QQ侧滑菜单:ResideMenu组件的使用笔记整理+Demo

    ResideMenu菜单 课堂笔记: https://github.com/SpecialCyCi/AndroidResideMenu Github:如何使用开源组件1. 下载 下载方式: 1. 项目 ...

  7. Netty的简单Demo

    这个demo是通过网上下载: 使用maven构建的: 项目结构: pom.xml: <dependencies> <dependency> <groupId>io. ...

  8. JavaMail发送邮件的笔记及Demo

    最近碰到一个需求,就是注册用户时候需要向用户发送激活邮箱,于是照着网上搜来的demo自己试着运行了一下,发件时我用的是网易163邮箱,收件时用QQ邮箱,运行后报了一个错误: 网络上搜索解决方式,多次尝 ...

  9. Netty笔记

    1 基本介绍 Bootstrap Netty应用程序通过设置 bootstrap(引导)类开始,该类提供了一个用于应用程序网络层配置的容器.Bootstrap有两种类型,一种是用于客户端的Bootst ...

随机推荐

  1. RESTful API概念解析

    什么是restful? REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”. ...

  2. Django权限控制进阶

    一.一级菜单的排序 我们用字典存放菜单信息,而字典是无序的,当一级菜单过多时可能会出现乱序情况,因此需要给一级菜单排序 1.给一级菜单表的model中加一个weight权重的字段 ,权重越大越靠前 w ...

  3. app.use和app.get的区别及解析

    转载至:http://blog.csdn.net/wthfeng/article/details/53366169 写在前面:最近研究nodejs及其web框架express,对app.use和app ...

  4. Anya and Cubes 搜索+map映射

    Anya loves to fold and stick. Today she decided to do just that. Anya has n cubes lying in a line an ...

  5. What Goes Up UVA - 481 LIS+打印路径 【模板】

    打印严格上升子序列: #include<iostream> #include<cstdio> #include<algorithm> #include<cst ...

  6. sqlserver 临时表,多用户同时访问冲突吗?

      当然不会冲突,一个井号的临时表(本地临时表),在数据库中物理表名并非你看到的,而是系统会为你的临时表生成一个唯一的表名,所以其它用户使用和建同样的表不会发生冲突.

  7. POJ1358 Agri-Net

    题目链接 就是裸的最小生成树,复习一下. prim算法: G=(V,E),V是点集,E是边集 假设T=(U,TE)是最小生成树.U,TE初始化为空 首先从V中任取一点 假设取V1,然后U={V1},只 ...

  8. HLS-搭建Nginx流媒体服务器

    Nginx本身是一个非常出色的HTTP服务器,FFMPEG是非常好的音视频解决方案.这两个东西通过一个nginx的模块nginx-rtmp-module,组合在一起即可以搭建一个功能相对比较完善的流媒 ...

  9. Loj 6432. 「PKUSC2018」真实排名 (组合数)

    题面 Loj 题解 枚举每一个点 分两种情况 翻倍or不翻倍 \(1.\)如果这个点\(i\)翻倍, 要保持排名不变,哪些必须翻倍,哪些可以翻倍? 必须翻倍: \(a[i] \leq a[x] < ...

  10. ssm框架中的乱码问题的解决

    在搭建ssm框架过程中可能会出现乱码的问题,解决的最好方法就是不管在哪儿都设置为utf-8: 统一编码格式,所有的都设置为utf-8: 首先的就是将所有的请求设置为utf-8: 设置post请求的编码 ...