netty: 将传递数据格式转为String,并使用分隔符发送多条数据
自定义分割符,用:DelimiterBasedFrameDecoder类
ByteBuf转String,用StringDecoder类
参考代码:
//设置连接符/分隔符,换行显示
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
//DelimiterBasedFrameDecoder:自定义分隔符
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf)); //设置为字符串形式的解码:将传递的buf改为String
sc.pipeline().addLast(new StringDecoder()); //处理数据
sc.pipeline().addLast(new ClientHandler());
完整代码:
client代码
public static void main(String[] args) throws InterruptedException {
EventLoopGroup worker = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
// TODO Auto-generated method stub
//设置连接符/分隔符,换行显示
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
//DelimiterBasedFrameDecoder:自定义分隔符
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
//设置为字符串形式的解码:将传递的buf改为String
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ClientHandler());
}
});
//连接端口
ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
cf.channel().writeAndFlush(Unpooled.copiedBuffer("aaa$_".getBytes()));
cf.channel().writeAndFlush(Unpooled.copiedBuffer("bbbbb$_".getBytes()));
cf.channel().writeAndFlush(Unpooled.copiedBuffer("cccccccc$_".getBytes()));
cf.channel().closeFuture().sync();
worker.shutdownGracefully();
}
clientHandler代码
public class ClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
//super.channelRead(ctx, msg);
try {
//在传输的时候已经将ByteBuf转为string
String str = (String)msg;
System.out.println("Client: " + str);
} finally {
// TODO: handle finally clause
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
}
}
Server代码:
public static void main(String[] args) throws InterruptedException {
//待client连接的线程
EventLoopGroup boss = new NioEventLoopGroup();
//处理事务的线程
EventLoopGroup worker = new NioEventLoopGroup();
//bootstarp辅助类,注册server服务
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.SO_SNDBUF, 32*1024)
.option(ChannelOption.SO_RCVBUF, 32*1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
// TODO Auto-generated method stub
//设置连接符,换行显示
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
//DelimiterBasedFrameDecoder:自定义分隔符
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
//将buf转string
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ServerHandler());
}
});
//指定监听接口
ChannelFuture cf = b.bind(8765).sync();
cf.channel().closeFuture().sync();
boss.shutdownGracefully();
worker.shutdownGracefully();
}
ServerHandler代码
public class ServerHandler extends ChannelHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
//super.channelRead(ctx, msg);
//handler设置了buf转String
String str = (String)msg;
System.out.println("Serer:" + str);
String response = "我是响应的数据$_";
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
//super.exceptionCaught(ctx, cause);
cause.printStackTrace();
ctx.close();
}
}
netty: 将传递数据格式转为String,并使用分隔符发送多条数据的更多相关文章
- netty: marshalling传递对象,传输附件GzipUtils
netty: marshalling传递对象,传输附件GzipUtils 前端与服务端传输文件时,需要双方需要进行解压缩,也就是Java序列化.可以使用java进行对象序列化,netty去传输,但ja ...
- java语言中Object转为String的几种形式
在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能.本文将对常用的转换方法进行一个总结.常用的方法有Object.toString(),(String)要转换的对象,St ...
- c# 传递Null的string值导致的调用C++的dll报错 Attempted to read or write protected memory.
c# 调用C++的dll报错 Attempted to read or write protected memory: 原因是:c# 传递Null的string值导致的,将Null改为string ...
- [C#]List<int>转string[],string[]转为string
// List<int>转string[] public string[] ListInt2StringArray(List<int> input) { return Arra ...
- inputStream输入流转为String对象(将String对象转为inputStream输入流)
不得不说org.apache.commons包下有很多实用的工具类. org.apache.commons.io.IOUtils; 要将inputStream输入流转为String对象,只需使用org ...
- 集合流之“将List<Integer>转为String并用逗号分割”
1.使用[流+Collectors]转换 import java.util.ArrayList; import java.util.List; import java.util.stream.Coll ...
- Netty——高级发送和接收数据handler处理器
netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...
- netty发送和接收数据handler处理器
netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...
- 快速获取表单多条数据,使用ajax传递给后台
当表单中有多条数据需要向后台传递时,一个一个的获取显然是不可取的办法,可以借助表单的serialize()方法获取. HTML: <form id="form"> &l ...
随机推荐
- python函数知识六 内置函数二、匿名函数与内置函数三(重要)
19.内置函数二 abs():绝对值 lst = [1,2,-3,1,2,-5] print([abs(i) for i in lst]) enumerate("可迭代对象",&q ...
- python基础 — Selenium 详细介绍
一.Selenium+Python环境搭建及配置 1.1 selenium 介绍 selenium 是一个 web 的自动化测试工具,不少学习功能自动化的同学开始首选 selenium ,因为它相比 ...
- Detecting GAN-generated Imagery using Color Cues
Abstract 论文创新点:分析流行GAN网络结构得知,GAN网络生成得图片在颜色处理与真实摄像机拍摄的照片存在不同,主要表现在两方面. 实验结果:证明了两种线索能够有效区分GAN生 ...
- LeetCode977.Squares of a Sorted Array
题目 977. Squares of a Sorted Array Given an array of integers A sorted in non-decreasing order, retur ...
- 为了防止页面重新自动加载,可以给a标签设置href="javascript:void(0);"
<a href="javascript:void(0);"></a> <!--按照格式要求,此处的0不能省略!! 虽然省略看上去也没什么影响.但是当发 ...
- Spring RestTemplate的使用示例
@Bean注册一个RestTemplate: 调用服务: 因为要参与网络传输,所以要实现序列化接口:
- PXC增量恢复添加节点(IST)
绕开SST通过IST方式添加Node到Percona XtraDB Cluster Gcache存储了所有的 writeset ,因此说这个集合的大小直接决定了允许其他节点宕机后多长时间内可以进行 ...
- 方法2:使用Jenkins构建Docker镜像 --SpringCloud
前提意义: SpringCloud微服务里包含多个文件夹,拉取仓库的所有代码,然后过根据选项参数使用maven编译打包指定目录的jar,然后再根据这个目录的Dockerfile文件制作Docker镜像 ...
- IdentityServer4:发布环境的数字签名证书
一,jwt的三个组成部件 先来看一个由IdentityServer颁发的一个标准令牌 eyJhbGciOiJSUzI1NiIsImtpZCI6IjBiNTE3ZjIzYWY0OGM4ZjkyZjExM ...
- 4: ES内执行Groovy脚本,做文档部分更新、执行判断改变操作类型
ES有内置的Groovy脚本执行内核,可以在命令的Json内嵌入Groovy脚本语句 前提数据: