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) # ...
随机推荐
- Django中直接执行SQL语句
欢迎加入python学习交流群 667279387 今天在django views.py看到同事写的代码里面有段关于数据库查询的语句.因为涉及多个表的查询,所以django 的models的查询无法满 ...
- 2017 ACM/ICPC 沈阳 G题 Infinite Fraction Path
The ant Welly now dedicates himself to urban infrastructure. He came to the kingdom of numbers and s ...
- ARTS-S EN0002-London HIV patient's remission spurs hope for curing AIDS
原文 A stem-cell treatment put a London cancer patient's HIV into remission, marking the second such r ...
- 在ASP.NET Core中使用托管启动(hosting startup)程序集,实现批量注册service
在启动ASPNET Core时可以从外部程序集向应用添加增强功能.例如,外部库可以用托管启动( hosting startup) 实现为应用程序提供附加配置(Configuration)或服务(ser ...
- 【Eureka】服务端和客户端
[Eureka]服务端和客户端 转载:https://www.cnblogs.com/yangchongxing/p/10778357.html Eureka服务端 1.添加依赖 <?xml v ...
- 【设计模式】代理模式-Proxy
转载:https://www.cnblogs.com/yangchongxing/p/7654725.html 代理模式定义如下: Provide a surrogate or placeholder ...
- Java开发数据库设计的14个技巧,你知道几个?
1. 原始单据与实体之间的关系 可以是一对一.一对多.多对多的关系.在一般情况下,它们是一对一的关系:即一张原始单据对应且只对应一个实体.在特殊情况下,它们可能是一对多或多对一的关系,即一张原始单证对 ...
- C++构造函数的几种使用方法
在C++中,有一种特殊的成员函数,他的名字和类相同,没有返回值,不需要用户显示调用,用户也无法调用,而是在创建对象的时候自动执行. 这种特殊的函数就是构造函数 Constructor 构造函数的名字与 ...
- Unity中文API参考手册
转载请标明原文地址:http://www.cnblogs.com/zhangyukof/p/6835582.html Unity5中文脚本手册 网页版 Unity API 执行顺序: Unity5中 ...
- NodeJS2-1环境&调试----CommonJS
CommonJS 每个文件是一个模块,有自己的作用域 在模块内部module变量代表模块本身 module.exports属性代表模块对外接口 require规则 /表示绝对路径,./表示型对于当前文 ...