pom

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>

Server服务端

package com.lzh.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* Created by 敲代码的卡卡罗特
* on 2018/8/12 17:31.
*/
public class Server {
public static void main(String[] arg){
//服务类
ServerBootstrap b = new ServerBootstrap(); //boss线程监听端口,worker线程负责数据读写
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
b = b.group(bossGroup,workerGroup);
b = b.option(ChannelOption.SO_BACKLOG, 128);
b = b.childOption(ChannelOption.SO_KEEPALIVE, true);
//设置niosocket工厂
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyServerHandler());//
}
}); try {
//绑定端口并启动去接收进来的连接
ChannelFuture f = b.bind(8888).sync();
// 这里会一直等待,直到socket被关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
/***
* 优雅关闭
*/
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} }
}

服务端的处理类

package com.lzh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil; import java.util.Date; /**
* Created by 敲代码的卡卡罗特
* on 2018/8/12 21:21.
*/
public class MyServerHandler extends ChannelHandlerAdapter { /***
* 这里我们覆盖了chanelRead()事件处理方法。
* 每当从客户端收到新的数据时,
* 这个方法会在收到消息时被调用,
* 这个例子中,收到的消息的类型是ByteBuf
* @param ctx 通道处理的上下文信息
* @param msg 接收的消息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
//读取客户端发来的信息
ByteBuf m = (ByteBuf) msg; // ByteBuf是netty提供的 System.out.println("client:"+m.toString(CharsetUtil.UTF_8)); //2两种打印信息的方法。都可以实现
/* byte[] b=new byte[m.readableBytes()];
m.readBytes(b);
System.out.println("client:"+new String(b,"utf-8"));*/
//向客户端写信息
String name="你好客户端:这是服务端返回的信息!";
ctx.writeAndFlush(Unpooled.copiedBuffer(name.getBytes()));
} /***
* 这个方法会在发生异常时触发
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
/***
* 发生异常后,关闭连接
*/
cause.printStackTrace();
ctx.close();
}
}

Client客户端

package com.lzh.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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.NioSocketChannel; /**
* Created by 敲代码的卡卡罗特
* on 2018/8/12 21:46.
*/
public class Client { public static void main(String[] arg){
/**
* 如果你只指定了一个EventLoopGroup,
* 那他就会即作为一个‘boss’线程,
* 也会作为一个‘workder’线程,
* 尽管客户端不需要使用到‘boss’线程。
*/
Bootstrap b = new Bootstrap(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyClientHandler());
}
}); try {
ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
//向服务端发送信息
f.channel().writeAndFlush(Unpooled.copiedBuffer("你好".getBytes())); f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
}

客户端的处理类

package com.lzh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil; /**
* Created by 敲代码的卡卡罗特
* on 2018/8/12 21:49.
*/
public class MyClientHandler extends ChannelHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
try {
//读取服务端发来的信息
ByteBuf m = (ByteBuf) msg; // ByteBuf是netty提供的
System.out.println("client:"+m.toString(CharsetUtil.UTF_8));
} catch (Exception e) {
e.printStackTrace();
} finally {
//当没有写操作的时候要把msg给清空。如果有写操作,就不用清空,因为写操作会自动把msg清空。这是netty的特性。
ReferenceCountUtil.release(msg);
} } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

netty有许多坑,建议你们多看官方文档

推荐:https://ifeve.com/netty5-user-guide/

netty的HelloWorld演示的更多相关文章

  1. 【OpenGL 学习笔记01】HelloWorld演示样例

    <<OpenGL Programming Guide>>这本书是看了忘,忘了又看,赶脚还是把笔记做一做心里比較踏实,哈哈. 我的主题是,好记性不如烂笔头. ========== ...

  2. Netty实现时间服务演示样例

    相关知识点: [1] ChannelGroup是一个容纳打开的通道实例的线程安全的集合,方便我们统一施加操作.所以在使用的过程中能够将一些相关的Channel归类为一个有意义的集合.关闭的通道会自己主 ...

  3. 【入门篇一】HelloWorld演示(2)

    一.传统使用 Spring 开发一个“HelloWorld”的 web 应用 1. 创建一个 web 项目并且导入相关 jar 包. 2. 创建一个 web.xml 3. 编写一个控制类(Contro ...

  4. openWRT学习之LUCI之中的一个helloworld演示样例

    备注1:本文 讲述的是原生的openWRT环境下的LUCI 备注2:本文參考了诸多资料.感谢网友分享.參考资料: http://www.cnblogs.com/zmkeil/archive/2013/ ...

  5. Netty实现心跳机制

    netty心跳机制示例,使用Netty实现心跳机制,使用netty4,IdleStateHandler 实现.Netty心跳机制,netty心跳检测,netty,心跳 本文假设你已经了解了Netty的 ...

  6. Struts2 的 helloworld

    配置步骤: 1.在你的strut2目录下找到例子项目,把它的 lib 下的jar拷贝到你的项目.例如我的:struts-2.3.24\apps\struts2-blank 2.struts-2.3.2 ...

  7. netty开发教程(一)

    Netty介绍 Netty is an asynchronous event-driven network application framework  for rapid development o ...

  8. Java11实战:模块化的 Netty RPC 服务项目

    Java11实战:模块化的 Netty RPC 服务项目 作者:枫叶lhz链接:https://www.jianshu.com/p/19b81178d8c1來源:简书简书著作权归作者所有,任何形式的转 ...

  9. day 4 Socket 和 NIO Netty

    Scoket通信--------这是一个例子,可以在这个例子的基础上进行相应的拓展,核心也是在多线程任务上进行修改 package cn.itcast.bigdata.socket; import j ...

随机推荐

  1. AHOI2013 差异 【后缀数组】

    题目分析: 求出height以后很明显跨越最小height的一定贡献是最小height,所以对于区间找出最小height再将区间对半分. 代码: #include<bits/stdc++.h&g ...

  2. Xadmin 组件基础使用以及全局配置

    xadmin 的安装 方式一 pip 安装 会因为编码问题导致报错 因此需要下载 更改 README.rst 后本地安装 详情点击这里 方式二 源码方式安装 在 github 上下载源码后 将 xad ...

  3. MT【297】任意四边形的一个向量性质

    在平面四边形$ABCD$中,已知$E,F,G,H$分别是棱$AB,BC,CD,DA$的中点,若$|EG|^2-|HF|^2=1,$设$|AD|=x,|BC|=y,|AB|=z,|CD|=1,$则$\d ...

  4. 【 HDU3294 】Girls' research (Manacher)

    BUPT2017 wintertraining(15) #5F HDU - 3294 题意 给定字母x,字符串变换一下: 'x'-1 -> 'z', 'x'->'a', 'x'+1-> ...

  5. notepad++设置(不断更新)

    1.主题设置 主题名称:Obsidian 字体字号:Courier New 10 设置方法: 设置---语言格式设置---选择主题,同时勾选“使用全局字体”“使用全局字体大小 补充一点: 修改两处地方 ...

  6. luogu P4299 首都

    题目描述 在X星球上有N个国家,每个国家占据着X星球的一座城市.由于国家之间是敌对关系,所以不同国家的两个城市是不会有公路相连的. X星球上战乱频发,如果A国打败了B国,那么B国将永远从这个星球消失, ...

  7. 杨辉三角 II

    题目描述 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行. 在杨辉三角中,每个数是它左上方和右上方的数的和. 示例: 输入: 3 输出: [1,3,3,1] 贴出代码 class ...

  8. javascript之复习(css属性值的计算)

    js取div的宽高咋办,css有content-box,border-box,padding-box,表现又不一样.好在有个offsetWidth, <style type="text ...

  9. 初入webform的杂七杂八

    客户端---IIS(Internet Information Services的缩写,意为互联网信息服务管理器)---.NET framework---数据库 1.Repeater控件:对应的集合有5 ...

  10. C# Winfrom 发送邮件验证码&Timer控件

    邮件发送: //定义一个全局的string类型的验证码: string yzm = ""; //定义一个字符串,这里面包含所有需要的验证码的元素: string a = " ...