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. Aizu2130-Billion Million Thousand-dp

    用dp求出最大的表达,再用dp求出.//然而并没有想出来 #include <cstdio> #include <string> #include <algorithm& ...

  2. C# 动态调用泛型方法

    static void Main(string[] args) { #region 具体类型可传递. Personal specifiedPersonal = new Personal(); Empl ...

  3. python深度学习库keras——安装

    TensorFlow安装keras需要在TensorFlow之上才能运行.所以这里安装TensorFlow.TensorFlow需要vs2015环境,需要wein64位环境,所以32位的小伙伴需要升级 ...

  4. 大学jsp实验6session

    1.session对象的使用 (1)设计一个简单的在线问卷调查程序,共有3个页面,分别是one.jsp.two.jsp.three.jsp. 其中,shiyan6_1_one.jsp页面效果如下图所示 ...

  5. Spring03-AOP

    一. AOP介绍 1. Aop介绍 AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编 ...

  6. Matplotlib学习---用matplotlib画面积图(area chart)

    这里利用Nathan Yau所著的<鲜活的数据:数据可视化指南>一书中的数据,学习画图. 数据地址:http://book.flowingdata.com/ch05/data/us-pop ...

  7. 2018-01微信小程序--直播

    一. 小程序直播支持的格式 目前小程序支付两种格式直播 1) flv格式直播 2) rtmp格式直播 二. 能够开通小程序直播的行业类目 由于直播需要资质, 并不是每个企业都能够开通小程序直播, 微信 ...

  8. 【刷题】LOJ 556 「Antileaf's Round」咱们去烧菜吧

    题目描述 你有 \(m\) 种物品,第 \(i\) 种物品的大小为 \(a_i\) ​,数量为 \(b_i\)​( \(b_i=0\) 表示有无限个). 你还有 \(n\) 个背包,体积分别为 \(1 ...

  9. IHttpHandler处理请求api

    使用IHttpHandler处理请求,实现webapi功能. 研究asp.net管道处理事件后,可用此法实现webapi功能. 测试环境 VS2017 WIN10 IIS10 集成模式 关键接口类两个 ...

  10. 持久化和公平分发.py

    1.消息持久化在实际应用中,可能会发生消费者收到Queue中的消息,但没有处理完成就宕机(或出现其他意外)的情况,这种情况下就可能会导致消息丢失.为了避免这种情况发生,我们可以要求消费者在消费完消息后 ...