自定义分割符,用: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,并使用分隔符发送多条数据的更多相关文章

  1. netty: marshalling传递对象,传输附件GzipUtils

    netty: marshalling传递对象,传输附件GzipUtils 前端与服务端传输文件时,需要双方需要进行解压缩,也就是Java序列化.可以使用java进行对象序列化,netty去传输,但ja ...

  2. java语言中Object转为String的几种形式

    在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能.本文将对常用的转换方法进行一个总结.常用的方法有Object.toString(),(String)要转换的对象,St ...

  3. 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 ...

  4. [C#]List<int>转string[],string[]转为string

    // List<int>转string[] public string[] ListInt2StringArray(List<int> input) { return Arra ...

  5. inputStream输入流转为String对象(将String对象转为inputStream输入流)

    不得不说org.apache.commons包下有很多实用的工具类. org.apache.commons.io.IOUtils; 要将inputStream输入流转为String对象,只需使用org ...

  6. 集合流之“将List<Integer>转为String并用逗号分割”

    1.使用[流+Collectors]转换 import java.util.ArrayList; import java.util.List; import java.util.stream.Coll ...

  7. Netty——高级发送和接收数据handler处理器

    netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...

  8. netty发送和接收数据handler处理器

    netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...

  9. 快速获取表单多条数据,使用ajax传递给后台

    当表单中有多条数据需要向后台传递时,一个一个的获取显然是不可取的办法,可以借助表单的serialize()方法获取. HTML: <form id="form"> &l ...

随机推荐

  1. C语言实现简单的计算器(加、减、乘、除)

    利用运算符做为swich  case 语句条件,实现简单程序的编写;并且对输入的运算做判断,除数为零也需做判断; #include<stdio.h> int add(int a, int ...

  2. Django模型层之单表操作

    Django模型层之单表操作 一 .ORM简介 我们在使用Django框架开发web应用的过程中,不可避免地会涉及到数据的管理操作(如增.删.改.查),而一旦谈到数据的管理操作,就需要用到数据库管理软 ...

  3. Linux进程的五个段

    目录 数据段 代码段 BSS段 堆(heap) 栈 数据段 用来存放可执行文件中已初始化的全局变量,换句话说就是存放程序静态分配的变量和全局变量: 代码段 代码段是用来存放可执行文件的操作指令,也就是 ...

  4. Scratch编程:打猎(十)

    “ 上节课的内容全部掌握了吗?反复练习了没有,编程最好的学习方法就是练习.练习.再练习.一定要记得多动手.多动脑筋哦~~” 01 — 游戏介绍 这节我们实现一个消灭猎物的射击游戏. 02 — 设计思路 ...

  5. Centos 6.10 安装 Jenkins

    前言 持续集成的概念 持续集成,Continuous integration ,简称CI. 持续集成正是针对这一类问题的一种软件开发实践.它倡导团队开发成员必须经常集成他们的工作,甚至每天都可能发生多 ...

  6. Java开发环境搭建(一)

    一.JDK与JRE JDK:Java Development Kit,Java开发工具包,是给开发人员使用的,其中包含了Java的开发工具,如java.javac.jar等命令,同时也包含了JRE. ...

  7. attr()与prop()区分图

  8. 【洛谷 P4137】 Rmq Problem / mex(主席树)

    题目链接 容易发现,可能答案只有\(0\).每个数,每个数\(+1\) 于是把这\(2n+1\)个数建立一个权值线段树,可持久化一下,每个节点记录这个子树中最后加入数加入的时间的最小值\(latest ...

  9. Java中BIO和NIO

    同步/异步.阻塞/非阻塞概念 同步异步 同步和异步关注的是消息通信机制 (synchronous communication/ asynchronous communication) 同步:在发出一个 ...

  10. OC 组合实现多继承

    OC无法完全先C++使用多继承,但可以采用组合的模式来代替继承模式.(协议实现)实现多继承的代码:举例现在ClassC需要继承ClassA中methodA.ClassB中methodB,具体的代码为: ...