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. git 出现错误时

    Your local changes to the following files would be overwritten by merge: 解决办法 如果希望保留生产服务器上所做的改动,仅仅并入 ...

  2. 蒟阵P3390 【模板】矩阵快速幂

    代码如下: #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> ...

  3. A - 敌兵布阵 HDU - 1166 线段树(多点修改当单点修改)

    线段树板子题练手用 #include<cstdio> using namespace std; ; int a[maxn],n; struct Node{ int l,r; long lo ...

  4. HDU4035 Maze 【树形DP】【期望DP】

    题目分析: 以前一直不会这个方法, 我好菜啊. 转移分为三个部分,一个是直接成功,一个是转移到E1,还有一个是转移到自己周围的一圈儿点. 如果是叶子那么只能转移到父亲,如果不是叶子可以把非叶子的转移代 ...

  5. 洛谷P2678跳石头题解

    题目 这个题也是一个很经典的题了.其主要思想也是二分答案,原因就是题目中只要出现最大值最小或最小值最大,这种描述十有八九就是二分答案. 这个题原题也是让我们求最短的跳跃距离的最大值. 显而易见,最大值 ...

  6. python爬取豆瓣前25个影片内容的正则表达式练习

    通过python正则表达式获取豆瓣top250的第一页的25个影片排名,影片名字,影片连接,导演,主演,上映日期,国家,剧情,评分,评价人数的内容 网页html内容: <ol class=&qu ...

  7. ram自己写?用IP?

    前言 ram这种东西,可以用ip方便,也可以自己写代码描述它. 以下讨论单口ram:8bit*256 流程 1.IP: 使用IP当然是最方便的事情啦,但可移植性差而且可定制性较差. 仿真波形: 2.V ...

  8. IntelliJ IDEA快捷键总结

    原文: IntelliJ IDEA快捷键 下面只列出Windows系统下的快捷键,Mac下的快捷键参考上面的链接. Remember these Shortcuts 功能 快捷键 Smart code ...

  9. NOIP经典基础模板总结

    date: 20180820 spj: 距离NOIP还有81天 目录 STL模板: priority_queue 的用法:重载<,struct cmpqueue 的用法 stack 的用法vec ...

  10. 一种使用 emwin 绘制图片的方法

    @2018-12-10 [小记] 使用官方 <GUIBuilder.exe> 软件里的 Image 控件,注意格式为 .bmp,这种方式是将图片数据直接转为十六进制数据存储至静态区 具体使 ...