netty接收大文件的方法

参考: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

 

转载于:https://www.cnblogs.com/JAYIT/p/7027533.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/448387.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

制动失灵

定义 制动过程中&#xff0c;由于制动器某些零部件的损坏或发生故障&#xff0c;使运动部件(或运动机械)不能保持停止状态或不能按要求停止运动的现象。制动失灵的原因 制动失灵的关键在于制动系统无法对汽车施加足够的制动力&#xff0c;包括制动液管路液位不足或进入…

webpack 入门,说一下那些不入流的知识点、module.exports{ } 中配置说明

先说说Vue-Cli&#xff08;Vue项目脚手架&#xff09; 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 关于它能干什么&#xff0c;就不再赘述了&#xff0c;我们主要谈谈生成的与webp…

myeclipse2013 jad反编译插件安装

https://blog.csdn.net/zhenshixian88/article/details/26454319 1. 下载插件工具 http://download.csdn.net/detail/zwj_lmss/6697259 2. 里面有两个文件 1).JAD.EXE随便找个地方丢进去(我是随便放哪边的,不过有的人有问题,最后放在了jdk的bin下面.可能他们没有配置环境变量);…

转向失控

定义 转向失控就是方向盘不管用了&#xff0c;打方向盘&#xff0c;但是前轮不动&#xff0c;不受方向盘控制。转向失控的原因 转向失控可能因为车辆过快、酒驾、疲劳、车况不佳、雨雪路滑等&#xff0c;还有转向机构中有零部件脱落、损坏、卡滞时&#xff0c;也会使转向机…

this 的指向问题

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 this的指向已经是一个老生常谈的问题&#xff0c;每逢面试都要去复习复习&#xff0c;近来巩固js的基础&#xff0c;决心彻底掌握这个知…

C++之全局函数和成员函数的转换

全局函数和成员函数 把全局函数转化成成员函数&#xff0c;通过this指针隐藏左操作数 Test add(Test &t1, Test &t2)》Test add(Test &t2) 把成员函数转换成全局函数&#xff0c;多了一个参数 void printAB()》void printAB(Test *pthis) 函数返回元素和返回引…

HDU 3916 Sequence Decomposition 【贪心】

这道题目的题意就是使用题目中所给的Gate 函数&#xff0c;模拟出输入的结果 当然我们分析的时候可以倒着来&#xff0c;就是拿输入去减 每次Gate 函数都会有一个有效范围 这道题目求的就是&#xff0c;找出一种模拟方法&#xff0c;使得最小的有效范围最大化。 是一道【贪心】…

爆胎

定义 即轮胎爆裂。车辆的缺气(轮胎胎压低于标准胎压)行驶时&#xff0c;随着胎压的下降&#xff0c;轮胎与地面的摩擦成倍增加&#xff0c;胎温急剧升高&#xff0c;轮胎变软&#xff0c;强度急剧下降。这种情况下&#xff0c;如果车辆高速行驶&#xff0c;就可能导致爆胎。…

不要再问我跨域的问题了

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 跨域这两个字就像一块狗皮膏药一样黏在每一个前端开发者身上&#xff0c;无论你在工作上或者面试中无可避免会遇到这个问题。为了应付面…

SSM集合

SSM集成 1. Spring和各个框架的整合 Spring目前是JavaWeb开发中最终的框架&#xff0c;提供一站式服务&#xff0c;可以其他各个框架整合集成 Spring整合方案 1.1. SSH ssh是早期的一种整合方案 Struts2 &#xff1a; Web层框架 Spring &#xff1a; 容器框架 Hibernate &#…

浅谈 CSRF 攻击方式

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 一.CSRF是什么&#xff1f; CSRF&#xff08;Cross-site request forgery&#xff09;&#xff0c;中文名称&#xff1a;跨站请求伪造&a…

C++之运算符重载(上)

1、概念 所谓重载&#xff0c;就是重新赋予新的含义。函数重载就是对一个已有的函数赋予新的含义&#xff0c;使之实现新功能&#xff0c;因此&#xff0c;一个函数名就可以用来代表不同功能的函数&#xff0c;也就是”一名多用”。 运算符也可以重载。实际上&#xff0c;我们…

手刹

定义 考手刹的专业称呼是辅助制动器&#xff0c;与制动器的原理不同&#xff0c;其是采用钢丝拉线连接到后制动蹄上&#xff0c;以对车子进行制动。作用 用于平地斜坡停车时制动&#xff0c;防止车子在无人状态下自动滑跑&#xff0c;逼免发生交通事故。工作原理 其原…

关于[super dealloc]

销毁一个对象时&#xff0c;需要重写系统的dealloc方法来释放当前类所拥有的对象&#xff0c;在dealloc方法中需要先释放当前类中所有的对象&#xff0c;然后再调用[super dealloc]释放父类中所拥有的对象。如先调用[super dealloc]将释放掉父类中所拥有的对象&#xff0c;当前…

C++之运算符重载(下)

4.提高 1.运算符重载机制 编译器实现运算符重载实际上就是通过函数重载实现的&#xff0c;可分为全局函数方式&#xff0c;也可分为成员函数方式进行重载&#xff0c;并没有改变原操作符的属性和语义。只是针对某个特定类定义一种新的数据类型操作。 2.重载赋值运算符 赋值…

Cookie / Session 的机制与安全

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 Cookie和Session是为了在无状态的HTTP协议之上维护会话状态&#xff0c;使得服务器可以知道当前是和哪个客户在打交道。本文来详细讨论C…

手动挡

定义 手动挡&#xff0c;即用手拨动变速杆才能改变变速器内的齿轮啮合置&#xff0c;改变传动比&#xff0c;从而达到变速的目的。作用 一方面提供了手动的乐趣 另外一方面就是通过手动自主控制转速&#xff0c;还可以迟延或提前换档。驾驶技巧 市区内应直视前方五…

Servlet快速入门及运行流程

一、Servlet快速入门 1.创建一个web工程 2.在JavaResource中src下创建一个包名称为com.myxq.servlet 3.在创建的servlet包当中创建一个class文件起名为FirstServlet 4.进入该class实现一个Servlet接口&#xff0c;实现它未实现的方法 重点看service方法在该方法当中写入一句话进…

C++之多继承

1.基础知识 1.1 类之间的关系 has-A&#xff0c;uses-A 和 is-A has-A 包含关系&#xff0c;用以描述一个类由多个“部件类”构成。实现has-A关系用类成员表示&#xff0c;即一个类中的数据成员是另一种已经定义的类。 常和构造函数初始化列表一起使用 uses-A 一个类部分地…

自动挡

定义 所谓自动挡&#xff0c;就是不用驾驶者去手动换档&#xff0c;车辆会根据行驶的速度和交通情况自动选择合适的档位行驶。作用 能根据路面状况自动变速&#xff0c;使驾驶者可以全神贯地注视路面交通而不会被换档搞得手忙脚乱。工作原理 自动变速器&#xff0c…