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) # ...
随机推荐
- nbuoj2780 旅游问题
题目:http://www.nbuoj.com/v8.83/Problems/Problem.php?pid=2780 题意:莫得题意 原以为是道究极蠢的贪心,但是被一发wa打脸,给上wa点,还是太年 ...
- UESTC-1964命运石之门(类似SPFA的BFS)
命运石之门 Time Limit: 1000 MS Memory Limit: 256 MB Submit Status "这一切都是命运石之门的选择!" 凶真博士发明了能 ...
- io流函数略解(java_input流)[二]
背景 在写这篇随笔之前,已经写了io流函数略解(java_File)(一),主要是总结了File的一些操作,以及一些源码介绍. 在Io实际应用中,实际上运用在如果会操作File,实际上很难写出一点能实 ...
- 深入理解 Java 泛型
- electron中JS报错:require is not defined的问题解决方法
Electron已经发布了6.0正式版,升级后发现原来能运行的代码报错提示require is not defined 解决办法: 修改创建BrowserWindow部分的相关代码,设置属性webPr ...
- css修改overflow滚动条默认样式
html代码 <div class="inner"> <div class="innerbox"> <p style=" ...
- 【hibernate】重写物理表名和列明
[hibernate]重写物理表名和列明 转载:https://www.cnblogs.com/yangchongxing/p/10357123.html 假设你的数据库命名有这样的需求,表都以 yc ...
- 什么是cookie?什么是session?session和cookie有什么区别?
在技术面试中,经常被问到“说说Cookie和Session的区别”,大家都知道,Session是存储在服务器端的,Cookie是存储在客户端的,然而如果让你更详细地说明,你能说出几点?今天个推君就和大 ...
- So Easy - 在Linux服务器上部署 .NET Core App
.NET Core 是微软提供的免费.跨平台和开源的开发框架,可以构建桌面应用程序.移动端应用程序.网络应用程序.物联网应用程序和游戏应用程序等.如果你是 Windows 平台下的 dotnet 开发 ...
- 浅析堆栈段,BBS段,数据段,代码段
文章目录 1. 进程,线程 2. 堆栈段 3. BBS段 4. 代码段 5. 数据段 6. 例子 7. 总结 1. 进程,线程 所谓进程是指在系统中能独立运行并作为资源分配的基本单位,程序段,数据段和 ...