今天写了一个helloworld版本的netty程序,跟大家分享一下:

首先需要的包是:netty-all-4.1.25.Final.jar

客户端:

StrClient.java

package client;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ChannelFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
*1. 搞一个Bootstrop 对象
*
*2. 封装Bootstrop 对象
*
*3. 写Handler类 也就是所有的业务逻辑
*
* @author zx
*
*/
public class StrClient {
//分配一个ip和端口号
private String host;
private int port;
private NioEventLoopGroup nioEventLoopGroup;
public StrClient(String host, int port) {
this.host = host;
this.port = port;
}

//启动项目 ip地址是 本地 端口号是888
public static void main(String[] args) throws InterruptedException {
new StrClient("localhost", 888).start();
}

public void start() throws InterruptedException {
try {
//客户端的引导类,启动网络客户端 Bootstrap有很多客户端的属性
Bootstrap bootstrap = new Bootstrap();
//可以理解成是一个线程池,用这个线程池来处理连接和接收数据
nioEventLoopGroup = new NioEventLoopGroup();
bootstrap.group(nioEventLoopGroup) //多线程处理,注册一下这个组
.channel(NioSocketChannel.class) //制定通道类型是NioSocketChannel
.remoteAddress(new InetSocketAddress(host, port)) //注册远程服务器的地址
.handler(new ChannelInitializer<SocketChannel>() {
//↑模板代码/
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//业务逻辑
ch.pipeline().addLast(new StrClientHandler());
}
//↓模板代码/
});
//开始连接服务器
ChannelFuture channelFuture = bootstrap.connect().sync(); //等到连接成功,否则一直阻塞线程
channelFuture.channel().closeFuture().sync(); //接收数据之后阻塞
} catch (Exception e) {
e.printStackTrace();
} finally {
nioEventLoopGroup.shutdownGracefully().sync();
}
}
}

StrClientHandler.java

package client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class StrClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

//客户端连接服务器后会调用 这里面可以发送请求
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client -> 开始连接服务器发送数据...");
byte[] bytes = "get current time".getBytes();
ByteBuf buffer = Unpooled.buffer(bytes.length); //构造一个数组存数据
buffer.writeBytes(bytes); //给buffer写数据 在数组里面写入的数据
ctx.writeAndFlush(buffer); //将这个信息交给上下文 进入pipline 如果有第二个Handler也会把这个数据给这第二个Handler
}

//从服务器端接到数据之后
@Override
protected void channelRead0(ChannelHandlerContext ch, ByteBuf msg) throws Exception {
System.out.println("client -> 读取服务器返回的对象...");
//反序列化
byte [] bytes = new byte [msg.readableBytes()]; //将这个2进制的数据写入数组里
msg.readBytes(bytes); //实际上是写入数组中
String messageBody = new String (bytes,"UTF-8");
System.out.println("client -> 接到数据,内容是: " + messageBody);
}

//发生异常的时候会调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//打印出错的原因
cause.printStackTrace();
//发生异常的时候就会关闭这个上下文,中断数据的传输
ctx.close();
}

}

服务端:

StrServer.java

package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class StrServer {
private int port;
private NioEventLoopGroup nioEventLoopGroup;

public StrServer(int port) {
this.port = port;
}

public static void main(String[] args) throws InterruptedException {
new StrServer(888).start();
}

private void start() throws InterruptedException {
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
nioEventLoopGroup = new NioEventLoopGroup();
serverBootstrap.group(nioEventLoopGroup)
.channel(NioServerSocketChannel.class)
.localAddress("localhost", port)
.childHandler(new ChannelInitializer<Channel>() {
//业务逻辑
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new StrServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind().sync();
System.out.println("Server -> 服务启动成功 监听端口, " + port);
channelFuture.channel().closeFuture().sync();
}catch (Exception e) {
e.printStackTrace();
} finally {
nioEventLoopGroup.shutdownGracefully().sync();
}
}
}

StrServerHandler.java

package server;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class StrServerHandler extends ChannelInboundHandlerAdapter {

/**
*
*@param ctx 上下文
*@param msg 传来的具体的数据
*
*/
//读取客户端发来的数据 这个方法会被调起,在服务器读取数据的时候
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server -> 接到数据,开始处理...");
ByteBuf buf = (ByteBuf)msg; //将传过来的ByteBuf强制转换
byte [] req = new byte[buf.readableBytes()]; //2进制数组
buf.readBytes(req); //将req的内容写到buf中
//反序列化
String requestbody = new String (req, "UTF-8");
System.out.println("Server -> 客户端请求数据是: " + requestbody);
System.out.println("Server -> 开始写回数据");
String currentTime = new Date().toString();
//封装了数据的输出
ByteBuf copiedBuffer = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(copiedBuffer);

}

//数据读取完成会调起
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}

//发生异常会被调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
cause.printStackTrace();
}
}

运行服务端和客户端的main即可启动服务,

1. 服务端准备接受客户端的请求信息;

2. 客户端请求: get currentTime 

3. 服务端获取到请求信息:get currentTime

4. 服务端准备返回数据: String responseBody = new Date() . toString();

5. 服务端返回数据

6. 客户端获取服务端返回的数据

转载于:https://www.cnblogs.com/zx947240023/p/9178843.html

netty Demo相关推荐

  1. 基于http的netty demo

    1.引入netty的pom <dependency><groupId>io.netty</groupId><artifactId>netty-all&l ...

  2. Netty应用:快速了解http各版本的特性 HttpServer的小demo

    HTTP协议 0.9版本 GET /index.html 服务端只能返回html格式,传输过程只能处理文字. 1.0版本 支持任何格式的内容,包括图像.视频.二进制等等 引入了POST命令.HEAD命 ...

  3. Netty 系列三(ByteBuf).

    一.概述和原理 网络数据传输的基本单位总是字节,Netty 提供了 ByteBuf 作为它的字节容器,既解决了 JDK API 的局限性,又为网络应用程序提供了更好的 API,ByteBuf 的优点: ...

  4. Netty1:初识Netty

    为什么使用Netty Netty是业界最流行的NIO框架之一,它的健壮性.功能.性能.可定制性.可扩展性在同类框架中都是首屈一指的,它已经得到了成百上千的商用项目的证明.对于为什么使用Netty这个话 ...

  5. Netty学习笔记(六) 简单的聊天室功能之WebSocket客户端开发实例

    在之前的Netty相关学习笔记中,学习了如何去实现聊天室的服务段,这里我们来实现聊天室的客户端,聊天室的客户端使用的是Html5和WebSocket实现,下面我们继续学习. 创建客户端 接着第五个笔记 ...

  6. maven netty 配置_Netty是业界最流行的NIO框架之一:初识Netty

    为什么使用Netty Netty是业界最流行的NIO框架之一,它的健壮性.功能.性能.可定制性.可扩展性在同类框架中都是首屈一指的,它已经得到了成百上千的商用项目的证明.对于为什么使用Netty这个话 ...

  7. NIO与Netty编程(三)之Netty编程

    1.概述 Netty是JBOSS提供的一个Java开源框架.Netty提供异步的,基于事件驱动的网络应用程序框架,用以快速开发高性能.高可靠性的网络IO程序. Netty是一个基于NIO的网络编程框架 ...

  8. Netty之Http与Websocket

    HTTP(应用层协议) 默认是80端口,最早推出于1991年 请求/响应 客户端: HttpResponseDecoder 解码器,处理服务端的响应 HttpRequestEncoder编码器,处理服 ...

  9. Netty私有协议栈 读书笔记

    1.数据结构定义 1)netty消息:NettyMessage 1 package com.cherry.netty.demo.protocolstack.pojo; 2 3 import com.c ...

最新文章

  1. 安装linux办公软件,Centos7如何安装开源办公软件Libreoffice
  2. Excel-开发者工具(WPS)
  3. c语言不允许有常量的是,C语言试卷第10套含答案.doc-资源下载人人文库网
  4. 从芯片到 AI 生态,52 岁英特尔的蜕变!
  5. 方法二 、属性 CLR学习第九课
  6. 国家开放大学-农村社会学-形考作业4
  7. MacOS技巧|Mac如何自定义触控栏Touch Bar?显示Touch Bar教程
  8. SCS【13】单细胞转录组之识别细胞对“基因集”的响应 (AUCell)
  9. 点线面的特点_设计三神器!点线面的基本特点与表现
  10. 我的电脑里顽固图标删除解决
  11. 听歌识曲也太牛了吧!只“音”奥秘在此……
  12. Windows配置互联网访问检测服务器-IspSrv
  13. 移远4G模块通信模块使用
  14. 单细胞分析:质控实操(五)
  15. 机器学习算法——概率类模型评估指标4(校准可靠性曲线及预测概率直方图)
  16. SQL 中的 IFNULL和NULLIF
  17. 瑞利分布理论和近似概率密度函数
  18. 软考知识点梳理--项目评估
  19. Java 吃货联盟系统(变量、数组)
  20. c语言*p和**p,c语言分析(*p)++和*p++的不同含义

热门文章

  1. 1.7编程基础之字符串_04石头剪子布
  2. 第69课 胡萝卜与骨头
  3. 第4课 防卫导弹(第十章 动态规划--DP)
  4. 微信小程序 自动解决分包大小问题_微信小程序分包加载设置
  5. Oracle笔记-Oracle基本结构及安装启动(windows版)
  6. Java工作笔记-Spring Boot封装Jedis实例
  7. C++设计模式-备忘录模式
  8. 数据结构-排序基础代码
  9. ios html字符转义字符串,iOS HTML特殊字符转译
  10. 进程管理程序java,运维经验分享(四)--关于 java进程管理的服务控制脚本编程思路分析...