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. U盘快速启动热键

    各个品牌电脑U盘快速启动热键如下:

  2. Mail.Ru Cup 2018 Round 3

    A:签到 #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> # ...

  3. 微信web开发者工具 移动调试

    1 下载 微信web开发者工具:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455784140 下载一个自己能用的版本: 2 ...

  4. P1319 压缩技术

    很多小伙伴卡在此题的原因可能是因为不知道怎么让它输入无限个数字吧?除了用string,在这里我是看到“压缩码保证 N * N=交替的各位数之和”这一句话,想到用while循环.只要输入的数的总和t小于 ...

  5. Codeforces Global Round 2 D. Frets On Fire (动态开点线段树,沙雕写法)

    题目链接:D. Frets On Fire 思路:明明可以离散化+二分写,思路硬是歪到了线段树上,自闭了,真实弟弟,怪不得其他人过得那么快 只和查询的区间长度有关系,排完序如果相邻的两个点的差值小于等 ...

  6. pax3 quick start guide

    pax3 quick start guide 外观图: 配置:1 * pax3 主机:2 * 吸嘴(一个平的,一个凸的):2 * 底盖(一个烟草的,一个烟膏的):3 * 过滤片:1 * USB充:1 ...

  7. fullcalendar 日历插件3.9.0 -- 基本插件使用

    以下主要结构,直接执行即可以使用 ,仅用参考: html: <!DOCTYPE html> <html> <head> <title>test</ ...

  8. LGP2801 教主的魔法

    题目链接 : P2801 教主的魔法 这是第一次A分块的题 就是模板题了 每个块内排序 每个整块仅需维护整块的修改量 询问操作: 对于边缘块 直接暴力找在[l, r]内 且比给定值大的有几个 对于整块 ...

  9. [CF976E]Well played!

    题目描述 Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" ...

  10. pip 安装第三方包提示Unknown or unsupported command 'install'

    Unknown or unsupported command 'install' Unknown or unsupported command 'show' Unknown or unsupporte ...