参考:http://blog.csdn.net/linuu/article/details/51371595

https://www.jianshu.com/p/a0a51fd79f62

netty默认是只能接收1024个字节,但是我们要传输大文件怎么办?

上代码:

改之后服务端:

package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import java.nio.charset.Charset; import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.eshore.ismp.hbinterface.service.BizCommonService;
import com.eshore.ismp.hbinterface.util.ConfigLoadUtil; public class SpsServer {
private static final Logger logger = Logger.getLogger(SpsServer.class);
private static int PORT = 10001;
/**用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认
/** 业务出现线程大小*/
protected static final int BIZTHREADSIZE = 4;
/*
* NioEventLoopGroup实际上就是个线程池,
* NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
* 每一个NioEventLoop负责处理m个Channel,
* NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
*/
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE); protected static void run(final BizCommonService bizCommonService) throws Exception {
String PORTs=ConfigLoadUtil.getValue("toSpsServerPort");
PORT=Integer.parseInt(PORTs);
logger.info("PORT IS:"+PORT);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
/* pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); */
ByteBuf delimiter = Unpooled.copiedBuffer("\t".getBytes());
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(2048,delimiter));
pipeline.addLast("decoder", new StringDecoder(Charset.forName("GBK")));
pipeline.addLast("encoder", new StringEncoder(Charset.forName("GBK")));
pipeline.addLast(new SpsServerHandler(bizCommonService));
}
}); b.bind(PORT).sync();
logger.info("TCP服务器已启动");
} protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} public static void main(String[] args) throws Exception {
try{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
context.start();
BizCommonService bizCommonService = (BizCommonService) context.getBean("bizCommonService");
SpsServer.run(bizCommonService);
}catch(Exception e){
logger.error("start sps interface server error:",e);
System.exit(-1);
}
}
}

改之后客户端:

package fourNoBlocking;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer; /**
*
* 发送报文给客户端
*
*
* @date 2016年12月14日 上午11:56:27
* @since 1.0
*/
public class SendClient { private static final String ENCODING = "GBK"; public static String send(String ip, int port, String sendStr, int timeout) {
long start = System.currentTimeMillis();
System.out.println(sendStr.length());
if (sendStr == null || "".equals(sendStr)) {
return "str is null";
}
Socket client = null;
OutputStream stream = null;
InputStream is = null; try {
client = new Socket();
InetSocketAddress address = new InetSocketAddress(ip, port);
client.connect(address); timeout = timeout >= 0 ? timeout : 3500;
client.setSoTimeout(timeout);
stream = client.getOutputStream();
is = client.getInputStream(); int len = 0; len = sendStr.getBytes(ENCODING).length;
ByteBuffer buf = ByteBuffer.allocate(len);
byte[] bytes = sendStr.getBytes(ENCODING);
buf.put(bytes);
stream.write(buf.array(), 0, len);
stream.flush();
String res = "";
int i = 0;
byte[] b = new byte[6555];
while ((i = is.read(b)) != -1) {
res = new String(b, 0, i);
System.out.println(res);
break;
}
long end = System.currentTimeMillis(); return res;
} catch (Exception e) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
.append(System.currentTimeMillis());
return strBuilder.toString();
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
.append(System.currentTimeMillis());
}
} if (stream != null) {
try {
stream.close();
} catch (IOException e) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
.append(System.currentTimeMillis());
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
.append(System.currentTimeMillis());
}
}
}
} public static void main(String[] args) {
String msg="";
msg="FFFF76623634010100102700170103IBSS017555 000000021800100023402287248808*766236340100200001178400003001785000030217860000302110000004075510100020SZ2000000054121442461020001241324186148310300593PM_DJDHHM||83456517||001#$PM_HYLX||0||001#$BA_MSMAN||海豚||001#$PM_DJQYYB||518000||001#$PM_DJQYMC||深圳市福田区人力资源服务中心||001#$PM_BHHM||83456517||001#$PM_DJQYDZ||福田区福强路深圳文化创意园世纪工艺品文化广场309栋B座1-3层||001#$PM_SFZDXY||XY02||001#$PM_DJKHXX||||001#$BA_MSDEPTNAME||12||001#$PM_DLS||DSL6||001#$PM_YWSLLB||SLLB01||001#$PM_SLDYSLSH||0||001#$PM_JFQ||01||001#$PM_DJHMGS||1||001#$PM_SRFJ||2||001#$PM_JFJG||1||001#$PM_YZ||30||001#$PM_DXFSSL||100||001#$PB_BILLINGTYPE||000000||005#$PB_USERTYPE||100002||005#$PB_USERCHAR||JFSX01||005#$BEGIN_DATE||20170607||005#$END_DATE||||005#$10400014DXMP214688722910700016号百信息服务中心10800010122810070411400006徐冬生115000088291816511600110114+企业名片行业版包月套餐,114+短信名片包月套餐_定价计划,114+企业名片行业版包月套餐赠送3个月套餐外等额话费优惠11700017755KH000293285120\t";
String x=SendClient.send("127.0.0.1", 10001, msg, 3500);
System.out.println("return string:"+x);
} }

处理类:

package server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.eshore.ismp.hbinterface.service.BizCommonService; public class SpsServerHandler extends SimpleChannelInboundHandler<Object> { private static final Logger logger = LoggerFactory.getLogger(SpsServerHandler.class);
private BizCommonService bizCommonService;
public SpsServerHandler(){}
public SpsServerHandler(BizCommonService bizCommonService){
this.bizCommonService=bizCommonService;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("SERVER接收到消息 msg:{}",msg);
long start = System.currentTimeMillis();
boolean result = bizCommonService.sendOperToCacheAysn(String.valueOf(msg));
/**
* step 3 : 创建响应报文
*/
String res = bizCommonService.createResponseStr(String.valueOf(msg),result);
long end = System.currentTimeMillis();
logger.debug("SpsServer request:{} res:{} time cost:{}ms",String.valueOf(msg),res,(end-start));
ctx.channel().writeAndFlush(res);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
logger.warn("Unexpected exception from downstream.", cause);
ctx.close();
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.info("client closed:"+ctx.channel().hashCode());
super.channelInactive(ctx);
}
}

输出:

length:1027

服务端增加了:

ByteBuf delimiter = Unpooled.copiedBuffer("\t".getBytes());
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(2048,delimiter));

客户端报文增加了

\t

netty接收大文件的方法的更多相关文章

  1. Linux培训教程 linux系统下分割大文件的方法

    在linux中分割大文件,比如一个5gb日志文件,需要把它分成多个小文件,分割后以利于普通的文本编辑器读取. 有时,需要传输20gb的大文件,Linux培训 教程件到另一台服务器,也需要把它分割成多个 ...

  2. php中读取大文件实现方法详解

    php中读取大文件实现方法详解 来源:   时间:2013-09-05 19:27:01   阅读数:6186 分享到:0 [导读] 本文章来给各位同学介绍php中读取大文件实现方法详解吧,有需要了解 ...

  3. Netty 5 传送大文件的方法

    Netty 5 提供了 一个ChunkedWriterHandler 来传送大文件,发送端如下: 添加chunedwriterhandler: ChannelPipeline p = ...; p.a ...

  4. python tcp黏包和struct模块解决方法,大文件传输方法及MD5校验

    一.TCP协议 粘包现象 和解决方案 黏包现象让我们基于tcp先制作一个远程执行命令的程序(命令ls -l ; lllllll ; pwd)执行远程命令的模块 需要用到模块subprocess sub ...

  5. Netty接收HTTP文件上传及文件下载

    文件上传 这个处理器的原理是接收HttpObject对象,按照HttpRequest,HttpContent来做处理,文件内容是在HttpContent消息带来的. 然后在HttpContent中一个 ...

  6. 转(Response.WriteFile 无法下载大文件解决方法)

    以前用Response.WriteFile(filename),但当遇到大文件时无法完整下载. 该方法最大的问题,它不是直接将数据抛到客户端,而是在服务器端(IIS)上缓存.当下载文件比较大时,服务器 ...

  7. 大文件读取方法(C#)

    之前都是用StreamReader.ReadLine方法逐行读取文件,自从.NET4有了File.ReadLines这一利器,就再也不用为大文件发愁了. File.ReadLines在整个文件读取到内 ...

  8. python读取大文件的方法及mmap内存映射模块

    python计算文件的行数和读取某一行内容的实现方法 :最简单的办法是把文件读入一个大的列表中,然后统计列表的长度.如果文件的路径是以参数的形式filepath传递的,那么只用一行代码就可以完成我们的 ...

  9. 把大象装进冰箱:HTTP传输大文件的方法

    上次我们谈到了HTTP报文里的div,知道了HTTP可以传输很多种类的数据,不仅是文本,也能传输图片,音频和视频.   早期互联网上传输的基本上都是只有几k大小的文本和小图片,现在的情况则大有不同.网 ...

随机推荐

  1. suid/guid用法 suid/guid详细解析

    suid/guid 我们在前面曾经提到过s u i d和g u i d.这种权限位近年来成为一个棘手的问题.很多系统供应商不允许实现这一位,或者即使它被置位,也完全忽略它的存在,因为它会带来安全性风险 ...

  2. C++ 模板详解 肥而不腻

    C++模板 模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数.返回值取得任意类型. 模板是一种对类型进行参数化的工具: 通常有 ...

  3. Virtex6 PCIe 超简版基础概念学习(二)

    Virtex6 PCIe 超简版基础概念学习(二) 分类:FPGAPCIe (2081)  (0)  举报  收藏 文档版本 开发工具 测试平台 工程名字 日期 作者 备注 V1.0 ise14.7 ...

  4. **alon_MM DMA Interface for PCIe使用详解

    在所从事的项目中需要用到PCIE和DMA,经过再三研究,反复查看相关资料,终于弄懂了**alon_MM DMA Interface for PCIe的使用方法. PCIE在fpga和上位机之间起着中间 ...

  5. keepalived virtual_router_id 44

    在同一局或网内如果有多个keepalived 的话 virtuall_router_id 44 (不能相同,但同一对,是一定相同)

  6. sensor dma alloc failed问题

    打印信息 [CAPTURE][printCapCapbility:93]:D/ driver:sunxi-vfe [CAPTURE][printCapCapbility:94]:D/ card:sun ...

  7. 《LAMP系统工程师实用教程》读书笔记(一)- linux常用命令

    图书馆看到就借回来啦,这本书虽然其貌不扬,对新手还是挺棒的.来学下shell脚本和php. 把书上不熟悉的命令和选项记录下. mkdir -v创建文件夹并返回信息 mkdir -m创建文件夹并设定权限 ...

  8. CR, LF, CR/LF区别与关系

    前言 在文本处理中,CR(Carriage Return),LF(Line Feed),CR/LF是不同操作系统上使用的换行符,具体如下: Dos和Windows采用回车+换行CR/LF表示下一行 而 ...

  9. [Linux内核]ctrl-z/fg/bg/nohup/setsid/()与&/disown/screen

    转自:https://my.oschina.net/alphajay/blog/65058 My Tips: Ctrl -z    ->   suspend fg           -> ...

  10. RP2836 OUT0-OUT7 对应关系

    ARM-IO9           OUT0        PA8 备用 P5-A4管脚,可以连接74HC164D级联 ARM-IO10         OUT7        PA1       3 ...