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. POJ 3580-SuperMemo-splay树

    很完整的splay操作.做了这题就可以当板子用了. #include <cstdio> #include <algorithm> #include <cstring> ...

  2. [HAOI2007] 修筑绿化带

    类型:单调队列 传送门:>Here< 题意:给出一个$M*N$的矩阵,每一个代表这一格土地的肥沃程度.现在要求修建一个$C*D$的矩形花坛,矩形绿化带的面积为$A*B$,要求花坛被包裹在绿 ...

  3. FFT算法小结

    都应该知道多项式是什么对吧(否则学什么多项式乘法) 我们用\(A(x)\)表示一个\(n-1\)次多项式,即\(A(x)=\sum_{i=0}^{n-1} {a_i}*x^i\) 例如\(A(x)=x ...

  4. 【BZOJ3814】【清华集训2014】简单回路 状压DP

    题目描述 给你一个\(n\times m\)的网格图和\(k\)个障碍,有\(q\)个询问,每次问你有多少个不同的不经过任何一个障碍点且经过\((x,y)\)与\((x+1,y)\)之间的简单回路 \ ...

  5. 500 OOPS: bad bool value in config file for: anon_world_readable_only Login failed.

    [root@hyc ~]# ftp 192.168.254.5 Connected to 192.168.254.5 (192.168.254.5). Welcome to blah FTP serv ...

  6. Java简单工厂模式(SimpleFactoryMode)

    何为简单工厂模式? 由一个工厂类根据传入的参数,动态创建并返回相应的具体的实例! 三个构成元素: 1.工厂类 2.抽象产品 3.具体产品 优点: 1.提高扩展性 2.隐藏具体的实现类,并不需要知道产品 ...

  7. 【UOJ#340】【清华集训2017】小 Y 和恐怖的奴隶主(矩阵快速幂,动态规划)

    [UOJ#340][清华集训2017]小 Y 和恐怖的奴隶主(矩阵快速幂,动态规划) 题面 UOJ 洛谷 题解 考虑如何暴力\(dp\). 设\(f[i][a][b][c]\)表示当前到了第\(i\) ...

  8. IncDec Sequence(差分)

    题意:给定一个序列,可以对一个区间进行加1或减1的操作,问最少需要多少次可以将序列的值一样. Solution 我们将序列差分,得到一个差分数组. 对于每一个区间操作,我们可以把它转化为在查分数组上某 ...

  9. BJWC2018上学路线

    题目描述 小B 所在的城市的道路构成了一个方形网格,它的西南角为(0,0),东北角为(N,M). 小B 家住在西南角,学校在东北角.现在有T 个路口进行施工,小B 不能通过这些路口.小B 喜欢走最短的 ...

  10. centos7/rhel7下配置PXE+Kickstart自动安装linux系统

    应用场景:临时安装一个系统或者批量安装linux系统,无需人工介入选择下一步,减少在安装系统上的时间浪费,提高工作效率. DHCP + TFTP + Syslinux + FTP + Kickstar ...