3、netty第二个例子,使用netty建立客户端,与服务端通讯
第一个例子中,建立了http的服务器端,可以直接使用curl命令,或者浏览器直接访问。
在第二个例子中,建立一个netty的客户端来主动发送请求,模拟浏览器发送请求。
这里先启动服务端,再启动客户端,启动客户端后,在 channelActive 方法中,主动向服务器端发送消息,服务器端channelRead0 方法中,接收到客户端的消息后,会再向客户端返回消息。客户端channelRead0方法中接收到消息再向客户端发送消息,依次往复。
同样的,按照顺序
client
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient {
public static void main(String[] args) throws InterruptedException {
//客户端只需要一个
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try{ Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new MyClientInitlalizer());
ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); //channelFuture.channel().writeAndFlush("first msg");//发送数据,其实应该写到handler的active方法中 channelFuture.channel().closeFuture().sync(); }finally {
eventLoopGroup.shutdownGracefully();
} }
}
Initlalizer
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 MyClientInitlalizer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline(); //添加解码器的handler
channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); channelPipeline.addLast(new LengthFieldPrepender(4));
//字符串的解码器
channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
//字符串的编码器
channelPipeline.addLast( new StringEncoder(CharsetUtil.UTF_8));
//自定义的处理器
channelPipeline.addLast(new MyClientHandler());
}
}
handler
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() + "," + msg);
System.out.println( "client output:" + msg); ctx.writeAndFlush("from client" + LocalDateTime.now());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
//super.exceptionCaught(ctx, cause);
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.channel().writeAndFlush("来自客户端的问候!");//通道连接之后,发送数据
super.channelActive(ctx);
}
}
sever中的handle
server中的server代码和第一个例子类似,initlializer和client中的一致,就不贴代码了。
public class MyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress() + "," + msg);
ctx.writeAndFlush("from serevber" + UUID.randomUUID());//消息返回
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
// super.exceptionCaught(ctx, cause);
}
}
3、netty第二个例子,使用netty建立客户端,与服务端通讯的更多相关文章
- Netty入门之客户端与服务端通信(二)
Netty入门之客户端与服务端通信(二) 一.简介 在上一篇博文中笔者写了关于Netty入门级的Hello World程序.书接上回,本博文是关于客户端与服务端的通信,感觉也没什么好说的了,直接上代码 ...
- Netty入门——客户端与服务端通信
Netty简介Netty是一个基于JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性.换句话说,Netty是一个NIO框架,使用它可以简单快速 ...
- [Java]Hessian客户端和服务端代码例子
简要说明:这是一个比较简单的hessian客户端和服务端,主要实现从客户端发送指定的数据量到服务端,然后服务端在将接收到的数据原封不动返回到客户端.设计该hessian客户端和服务端的初衷是为了做一个 ...
- Java基础---Java---网络编程---TCP的传输、客户端和服务端的互访、建立一个文本转换器、编写一个聊天程序
演示TCP的传输的客户端和服务端的互访 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息. 客户端: 1.建立Socket服务,指定要连接方朵和端口 2.获取Socket流中的输出流,将数 ...
- Netty实现客户端和服务端通信简单例子
Netty是建立在NIO基础之上,Netty在NIO之上又提供了更高层次的抽象. 在Netty里面,Accept连接可以使用单独的线程池去处理,读写操作又是另外的线程池来处理. Accept连接和读写 ...
- 【Netty源码分析】客户端connect服务端过程
上一篇博客[Netty源码分析]Netty服务端bind端口过程 我们介绍了服务端绑定端口的过程,这一篇博客我们介绍一下客户端连接服务端的过程. ChannelFuture future = boos ...
- tcp,第一个例子,客户端,服务端
1.客户端 package cd.itcast.xieyi; import java.io.IOException; import java.io.OutputStream; import java. ...
- thrift例子:python客户端/java服务端
java服务端的代码请看上文. 1.说明: 这两篇文章其实解决的问题是,当使用python去访问大数据线上集群的时候,遇到两个问题: 1)python-hadoop和python-hive相关包链接不 ...
- python7.3客户端、服务端的建立
import socket #创建客户端client=socket.socket() #生成socket连接对象client.connect("localhost",6969) # ...
随机推荐
- 洛谷 题解 2165 [AHOI2009]飞行棋
本蒟蒻又来发题解了, 看到这个题目,本蒟蒻直接开始推公式.. 嗯,可以通过弧长,推出弦长(l = 2 * r * cos(90 * l / (r * Π)); 然后对比各条弦长的平方和与直径的平方. ...
- 洛谷 题解 SP3267 【DQUERY - D-query】
今天机房讲了莫队. 但是蒟蒻我并没有听懂,所以晚上回家恶补,才弄明白莫队. 莫队是莫涛大神发明的,它的作用就是用优秀的复杂度求解于一些区间之间的操作,莫队其实就是一个优雅的暴力,它的复杂度是O(n s ...
- luogu P2740 [USACO4.2]草地排水Drainage Ditches |网络流
题目背景 在农夫约翰的农场上,每逢下雨,贝茜最喜欢的三叶草地就积聚了一潭水.这意味着草地被水淹没了,并且小草要继续生长还要花相当长一段时间.因此,农夫约翰修建了一套排水系统来使贝茜的草地免除被大水淹没 ...
- luogu P3984 高兴的津津
题目描述 津津上高中了.她在自己的妈妈的魔鬼训练下,成为了一个神犇,每次参加一次OI比赛必拿Au虐全场.每次她拿到一个Au后就很高兴.假设津津不会因为其它事高兴,并且她的高兴会持续T天(包包含获奖当天 ...
- 【重学Node.js 第3篇】mongodb以及mongoose的使用
mongodb以及mongoose的使用 本篇为这个系列的第三篇,想看更多可以直接去github的项目:https://github.com/hellozhangran/happy-egg-serve ...
- UIScrollView,UICollectionView 和UITableView的属性和方法
UIScrollView,UICollectionView 和UITableView 三者之间的关系:UIScrollView是 UICollectionView 和 UITableView 的父类. ...
- 数据库Oracle日期函数
SYSDATE 函数:是一个日期函数,它返回当前数据库服务器的日期和时间. 用日期计算: • 从日期加或者减一个数,结果是一个日期值 • 两个日期相减,得到两个日期之间的天数 ,可以加小时到日期上 S ...
- HDU5002 tree
You are given a tree with N nodes which are numbered by integers 1..N. Each node is associated with ...
- Codeforce612C
You are given string s consists of opening and closing brackets of four kinds <>,{}, [], (). T ...
- HDU-1698-----Just Hook
In the game of DotA, Pudge's meat hook is actually the most horrible thing for most of the heroes. T ...