《精通并发与Netty》学习笔记(03 - 客户端程序编写)
上节我们编写了netty服务端的程序,这节我们来写客户端程序
第一步:改造服务端程序为:
(1)MyServer类:
package com.ssy.netty.demo01; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; /**
* netty作为长连接的服务器基于websoket,实现客户端与服务器端长连接。
*/
public class MyServer {
public static void main(String[] args) {
//负责接收客户端连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//处理连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup) // 绑定线程池
.channel(NioServerSocketChannel.class)
.childHandler(new MyServerInitializer()); //绑定端口号
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
(2)MyServerInitializer类
package com.ssy.netty.demo01; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; /**
* 绑定客户端连接时候触发操作
*/
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//负载http 请求编码解码
//pipeline.addLast("httpServerCodec",new HttpServerCodec());
//实际处理请求
//pipeline.addLast("httpServerHandler",new HttpServerHandler());
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyServerHandler());
}
}
(3)MyServerHandler类
package com.ssy.netty.demo01; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import java.time.LocalDateTime; public class MyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress());
System.out.println("client output:"+msg);
ctx.writeAndFlush("from server:" + LocalDateTime.now());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
编写客户端主程序MyClient
package com.ssy.netty.demo01; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient {
public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup) // 绑定线程池
.channel(NioSocketChannel.class)
.handler(new MyClientInitializer()); //绑定端口号
ChannelFuture channelFuture = bootstrap.connect("localhost",8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
eventLoopGroup.shutdownGracefully();
}
}
}
第二步:编写MyClientInitializer
package com.ssy.netty.demo01; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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; public class MyClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyClientHandler());
}
}
第三步:编写MyClientHandler
package com.ssy.netty.demo01; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import java.time.LocalDateTime; public class MyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress());
System.out.println("client output:"+msg);
ctx.writeAndFlush("from client:" + LocalDateTime.now());
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("来自客户端的问候");
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
分别启动MyServer程序和MyClient程序,客户端成功调用服务端。
到此为止,我们已经完成了简单的netty服务端与客户端的通信程序,下节我们会对谷歌的Google Protobuf做一次详解,敬请期待吧!
《精通并发与Netty》学习笔记(03 - 客户端程序编写)的更多相关文章
- 《精通并发与Netty》学习笔记(01 - netty介绍及环境搭建)
一.Netty介绍 Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序. ...
- Netty学习笔记(二) 实现服务端和客户端
在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...
- Netty学习笔记-入门版
目录 Netty学习笔记 前言 什么是Netty IO基础 概念说明 IO简单介绍 用户空间与内核空间 进程(Process) 线程(thread) 程序和进程 进程切换 进程阻塞 文件描述符 文件句 ...
- Netty 学习笔记(1)通信原理
前言 本文主要从 select 和 epoll 系统调用入手,来打开 Netty 的大门,从认识 Netty 的基础原理 —— I/O 多路复用模型开始. Netty 的通信原理 Netty 底层 ...
- Mina框架的学习笔记——Android客户端的实现
Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络 ...
- 精通并发与 Netty (一)如何使用
精通并发与 Netty Netty 是一个异步的,事件驱动的网络通信框架,用于高性能的基于协议的客户端和服务端的开发. 异步指的是会立即返回,并不知道到底发送过去没有,成功没有,一般都会使用监听器来监 ...
- Redis:学习笔记-03
Redis:学习笔记-03 该部分内容,参考了 bilibili 上讲解 Redis 中,观看数最多的课程 Redis最新超详细版教程通俗易懂,来自 UP主 遇见狂神说 7. Redis配置文件 启动 ...
- 机器学习实战(Machine Learning in Action)学习笔记————03.决策树原理、源码解析及测试
机器学习实战(Machine Learning in Action)学习笔记————03.决策树原理.源码解析及测试 关键字:决策树.python.源码解析.测试作者:米仓山下时间:2018-10-2 ...
- OpenCV 学习笔记03 边界框、最小矩形区域和最小闭圆的轮廓
本节代码使用的opencv-python 4.0.1,numpy 1.15.4 + mkl 使用图片为 Mjolnir_Round_Car_Magnet_300x300.jpg 代码如下: impor ...
随机推荐
- 关于maven依赖死活都下载不了终极解决方案
项目想下载一个依赖,在idea中死都下不了,查看网上各种解决方案都没有效果,出绝招,我使用命令下载jar然后导入到项目引用的maven仓库 类似这种命令:mvn install:install-fil ...
- esxi克隆虚拟机
1.->选中虚拟机->导出(需要关闭虚拟机电源) 此时会下载下两个文件: 2.新建虚拟机 ->从OVF或OVA文件部署虚拟机 然后创建虚拟机,选择第二项 然后填入新虚拟机名称,并把下 ...
- Filter和interceptor比较
作为一个备忘,有时间补充 https://www.cnblogs.com/learnhow/p/5694876.html 先说一个题外话,Filter是过滤器,interceptor是拦截器.前者基于 ...
- [2019牛客多校第二场][G. Polygons]
题目链接:https://ac.nowcoder.com/acm/contest/882/G 题目大意:有\(n\)条直线将平面分成若干个区域,要求处理\(m\)次询问:求第\(q\)大的区域面积.保 ...
- Elasticsearch7.1中文文档-第一章-入门
安装openjdk wget --no-cookies --no-check-certificate --header "Cookie: oraclelicense=accept-secur ...
- SQL SERVER 表添加新字段
SQL SERVER 表添加新字段 ALTER TABLE doc_exa ADD column_b VARCHAR(20) NULL; -- doc_exa 是表名 -- column_b 是新加的 ...
- UVALive 7308 Tom and Jerry 猫抓老鼠 物理题
题目链接: 就是一个老鼠在环上一速度v开始绕环走,一只猫从圆心出发,任意时刻圆心,猫,老鼠三者在一条直线上,且速度也是v,求多久后猫抓到老鼠. #include <cstdio> #inc ...
- AVL平衡树(非指针实现)
看了网上三四篇博客,学习了AVL树维护平衡的方式.但感觉他们给出的代码都有一点瑕疵或者遗漏,懂得了思想之后,花了一些时间把他们几篇的长处结合起来,没有使用指针,实现了一下.每个小逻辑功能都抽象成了函数 ...
- Java基础_死锁、线程组、定时器Timer
一.死锁问题: 死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放.由于线程被无限期地阻塞,因此程序不可能正常终止. 比如,线程一需要第一把所,此时锁处于空闲状态,给了 ...
- 部署Hadoop2.0高性能集群
废话不多说直接实战,部署Hadoop高性能集群: 拓扑图: 一.实验前期环境准备: 1.三台主机配置hosts文件:(复制到另外两台主机上) [root@tiandong63 ~]# more /et ...