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.pswp.cn/news/448387.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/448387.shtml
英文地址,請注明出處:http://en.pswp.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…