http stream

博客分类:

      http://canofy.iteye.com/blog/2097876
 
  1. StringBuilder sb = new StringBuilder();
  2. sb.append("HTTP/1.1 200 OK\r\n");
  3. sb.append("Content-Type: text/plain\r\n");
  4. sb.append("Transfer-Encoding: chunked\r\n\r\n");
  5. sb.append("25\r\n");
  6. sb.append("This is the data in the first chunk\r\n"); // 37 bytes
  7. sb.append("\r\n1A\r\n");
  8. sb.append("and this is the second one"); // 26 bytes
  9. sb.append("\r\n0\r\n\r\n");

十六进制包长+\r\n+报文包+\r\n  为一个传输单元

0+\r\n+\r\n 当遇到这种空传输单元时结束

下面是客户端例子

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.InetSocketAddress;
  6. import java.net.Socket;
  7. import java.nio.ByteBuffer;
  8. import java.nio.channels.SocketChannel;
  9. import java.util.concurrent.Callable;
  10. import java.util.concurrent.ExecutorService;
  11. import java.util.concurrent.Executors;
  12. import java.util.concurrent.FutureTask;
  13. public class Client {
  14. public boolean isAsync=false;
  15. /**
  16. * 建立socket
  17. * @param ip
  18. * @param port
  19. * @return
  20. * @throws IOException
  21. * @throws NumberFormatException
  22. * @throws PachiraAsrSocketCreateException
  23. */
  24. protected SocketChannel createSocketChannel(String ip,String port) throws NumberFormatException, IOException {
  25. SocketChannel socketChannel=null;
  26. if(isAsync){
  27. socketChannel = SocketChannel.open();
  28. socketChannel.configureBlocking(false);
  29. //向服务端发起连接
  30. if (!socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)))){
  31. //不断地轮询连接状态,直到完成连接
  32. while (!socketChannel.finishConnect()){
  33. //在等待连接的时间里,可以执行其他任务,以充分发挥非阻塞IO的异步特性
  34. //这里为了演示该方法的使用,只是一直打印"."
  35. try {
  36. Thread.sleep(10);
  37. } catch (InterruptedException e) {
  38. }
  39. //                      SrvLogger.debug(getClass(), "");
  40. }
  41. }
  42. }else{
  43. socketChannel = SocketChannel.open();
  44. socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)));
  45. }
  46. return socketChannel;
  47. }
  48. /**
  49. * 关闭socket
  50. * @param socketChannel
  51. * @param uuid
  52. * @throws IOException
  53. */
  54. protected void closeSocketChannel(SocketChannel socketChannel) throws IOException{
  55. if(socketChannel!=null){
  56. socketChannel.close();
  57. }
  58. }
  59. /**
  60. * 传输数据
  61. * @param socket
  62. * @param in
  63. * @param uuid
  64. * @param audioType
  65. * @throws IOException
  66. */
  67. protected boolean sendStringData(final SocketChannel socketChannel ,final String str) throws IOException{
  68. ByteBuffer buffer=ByteBuffer.wrap(str.getBytes(), 0, str.length());
  69. int size=0;
  70. int wl=0;
  71. System.out.println("buf.limit="+buffer.limit());
  72. wl=socketChannel.write(buffer);
  73. while (buffer.hasRemaining()) {
  74. if (wl < 0){
  75. System.out.println("sendData len is -1;size="+size);
  76. break;
  77. }
  78. if (wl == 0) {
  79. System.out.println("sendData len is 0 ;size="+size);
  80. }
  81. size+=wl;
  82. }
  83. buffer.flip();
  84. return true;
  85. }
  86. /**
  87. * 传输数据
  88. * @param socket
  89. * @param in
  90. * @param uuid
  91. * @param audioType
  92. */
  93. protected boolean sendData(final SocketChannel socketChannel ,final InputStream is){
  94. FutureTask<Integer> task  = new FutureTask<Integer>(new Callable<Integer>(){
  95. public Integer call() {
  96. System.out.println("sendData start...;");
  97. byte[] buf = new byte[8096];
  98. int totalSize=0;
  99. int sendTotalSize=0;
  100. try {
  101. int read = is.read(buf, 0, buf.length);
  102. while (read > 0) {
  103. totalSize+=read;
  104. ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
  105. int size=0;
  106. int wl=0;
  107. wl=socketChannel.write(buffer);
  108. while (buffer.hasRemaining()) {
  109. if (wl < 0){
  110. System.out.println("sendData len is -1;size="+size);
  111. break;
  112. }
  113. if (wl == 0) {
  114. System.out.println("sendData len is 0 ;size="+size);
  115. }
  116. size+=wl;
  117. }
  118. buffer.flip();
  119. sendTotalSize+=read;
  120. read = is.read(buf, 0, buf.length);
  121. }
  122. sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
  123. System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
  124. }catch (Exception e) {
  125. e.printStackTrace();
  126. }finally{
  127. }
  128. return new Integer(8);
  129. }
  130. });
  131. ExecutorService sendDataPool=Executors.newCachedThreadPool();
  132. sendDataPool.execute(task);
  133. return true;
  134. }
  135. /**
  136. * 传输数据
  137. * 十六进制包长+\r\n+报文包+\r\n  为一个传输单元
  138. 0+\r\n+\r\n 当遇到这种空传输单元时结束
  139. * @param socket
  140. * @param in
  141. * @param uuid
  142. * @param audioType
  143. */
  144. protected boolean sendDataChunk(final SocketChannel socketChannel ,final InputStream is){
  145. FutureTask<Integer> task  = new FutureTask<Integer>(new Callable<Integer>(){
  146. public Integer call() throws IOException {
  147. System.out.println("sendData start...;");
  148. sendStringData(socketChannel, "\r\n");
  149. String parameter="------------V2ymHFg03ehbqgZCaKO6jy\r\nContent-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";\r\n\r\n";
  150. sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
  151. sendStringData(socketChannel, parameter+"\r\n");
  152. //                  sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
  153. //                  sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
  154. //                  sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
  155. //                  sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
  156. //                  sendStringData(socketChannel, Integer.toHexString("------------V2ymHFg03ehbqgZCaKO6jy".length())+"\r\n");
  157. //                  sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy\r\n");
  158. //                  String parameter="Content-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";";
  159. //                  sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
  160. //                  sendStringData(socketChannel, parameter+"\r\n");
  161. byte[] buf = new byte[8096];
  162. int totalSize=0;
  163. int sendTotalSize=0;
  164. try {
  165. int read = is.read(buf, 0, buf.length);
  166. while (read > 0) {
  167. totalSize+=read;
  168. ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
  169. String hex= Integer.toHexString(read);
  170. System.out.println("read="+read+";hex="+hex);
  171. sendStringData(socketChannel,hex+"\r\n");
  172. int size=0;
  173. int wl=0;
  174. //                          System.out.println("send..");
  175. wl=socketChannel.write(buffer);
  176. //                          System.out.println("send...");
  177. while (buffer.hasRemaining()) {
  178. if (wl < 0){
  179. System.out.println("sendData len is -1;size="+size);
  180. break;
  181. }
  182. if (wl == 0) {
  183. System.out.println("sendData len is 0 ;size="+size);
  184. }
  185. size+=wl;
  186. }
  187. sendStringData(socketChannel, "\r\n");
  188. buffer.flip();
  189. sendTotalSize+=read;
  190. read = is.read(buf, 0, buf.length);
  191. Thread.sleep(50);
  192. }
  193. sendStringData(socketChannel, Integer.toHexString("------------V2ynHFg03ehbqgZCaKO6jy--".length())+"\r\n");
  194. sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
  195. sendStringData(socketChannel, "\r\n");
  196. sendStringData(socketChannel, "0\r\n\r\n");
  197. System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
  198. }catch (Exception e) {
  199. e.printStackTrace();
  200. }finally{
  201. }
  202. return new Integer(8);
  203. }
  204. });
  205. ExecutorService sendDataPool=Executors.newCachedThreadPool();
  206. sendDataPool.execute(task);
  207. return true;
  208. }
  209. /**
  210. * 读取
  211. * @param inputStream
  212. * @param buf
  213. * @return
  214. * @throws IOException
  215. */
  216. protected boolean readData(SocketChannel socketChannel, ByteBuffer buf) {
  217. boolean ret = true;
  218. long count=0;
  219. try {
  220. count = socketChannel.read(buf);
  221. //          if(this.isAsync){
  222. while(count<buf.limit()){
  223. if(count==-1){
  224. System.out.println("readData count is -1");
  225. return false;
  226. }
  227. count += socketChannel.read(buf);
  228. try {
  229. Thread.sleep(10);
  230. } catch (InterruptedException e) {
  231. return false;
  232. }
  233. }
  234. //              System.out.println("buffer.position()="+buf.position()+";buffer.limit()="+buf.limit());
  235. //              System.out.println("count="+count);
  236. //          }
  237. if(count>0){
  238. buf.flip();
  239. }
  240. } catch (Exception e) {
  241. ret=false;
  242. }finally{
  243. System.out.println("readData count="+count+";bufLen="+buf.limit());
  244. }
  245. return ret;
  246. }
  247. /**
  248. * 读取
  249. * @param inputStream
  250. * @param buf
  251. * @return
  252. * @throws IOException
  253. */
  254. protected boolean readDataBySocket(SocketChannel socketChannel) throws IOException {
  255. Socket socket=socketChannel.socket();
  256. InputStream in=socket.getInputStream();
  257. byte[] buf1=new byte[7];
  258. while(this.read(in, buf1)){
  259. System.out.println("result"+new String(buf1));
  260. }
  261. return false;
  262. }
  263. protected boolean read(InputStream inputStream, byte[] buf)
  264. throws IOException {
  265. boolean ret = true;
  266. int totalSize = buf.length;
  267. int read = inputStream.read(buf, 0, buf.length);
  268. while (read < totalSize) {
  269. read += inputStream.read(buf, read, (totalSize - read));
  270. }
  271. return ret;
  272. }
  273. public void nonstream() throws IOException{
  274. String ip="127.0.0.1";
  275. String port="8080";
  276. File file=new File("I:/1/pase/90s_9.wav");
  277. FileInputStream fis=new FileInputStream(file);
  278. SocketChannel socketChannel=createSocketChannel(ip, port);
  279. String parameter="------------V2ynHFg03ehbqgZCaKO6jy\r\nContent-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"0\";";
  280. sendStringData(socketChannel, "POST /project/uploader HTTP/1.1\r\n");
  281. sendStringData(socketChannel, "Accept: */*\r\n");
  282. sendStringData(socketChannel, "User-Agent: Mozilla/4.0\r\n");
  283. sendStringData(socketChannel, "Content-Length: "+(file.length()+parameter.length())+"\r\n");
  284. sendStringData(socketChannel, "Accept-Language: en-us\r\n");
  285. sendStringData(socketChannel, "Accept-Encoding: gzip, deflate\r\n");
  286. sendStringData(socketChannel, "Host: 127.0.0.1\r\n");
  287. sendStringData(socketChannel, "Content-Type: multipart/form-data;boundary=----------V2ymHFg03ehbqgZCaKO6jy\r\n");
  288. sendStringData(socketChannel, "\r\n");
  289. sendStringData(socketChannel, parameter+"\r\n");
  290. sendStringData(socketChannel, "\r\n");
  291. //send file1449930
  292. sendData(socketChannel, fis);
  293. //      client.sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
  294. ByteBuffer bb=ByteBuffer.allocate(2000);
  295. readData(socketChannel, bb);
  296. byte[] b=new byte[bb.limit()];
  297. bb.get(b, 0, bb.limit()-1);
  298. System.out.println(new String(b));
  299. }
  300. public static void main(String[] args) throws NumberFormatException, IOException {
  301. String ip="localhost";
  302. String port="8080";
  303. Client client=new Client();
  304. //      File file=new File("I:/1/a.txt");
  305. File file=new File("I:/1/pase/90s_9.wav");
  306. FileInputStream fis=new FileInputStream(file);
  307. SocketChannel socketChannel=client.createSocketChannel(ip, port);
  308. client.sendStringData(socketChannel, "POST /project/uploader HTTP/1.1\r\n");
  309. client.sendStringData(socketChannel, "Accept: */*\r\n");
  310. client.sendStringData(socketChannel, "User-Agent: Mozilla/4.0\r\n");
  311. //      client.sendStringData(socketChannel, "Content-Length: "+(file.length()+parameter.length())+"\r\n");
  312. client.sendStringData(socketChannel, "Transfer-Encoding: chunked\r\n");
  313. client.sendStringData(socketChannel, "Accept-Language: en-us\r\n");
  314. client.sendStringData(socketChannel, "Accept-Encoding: gzip, deflate\r\n");
  315. client.sendStringData(socketChannel, "Host: 127.0.0.1\r\n");
  316. client.sendStringData(socketChannel, "Content-Type: multipart/form-data;boundary=----------V2ynHFg03ehbqgZCaKO6jy\r\n");
  317. //send file1449930
  318. client.sendDataChunk(socketChannel, fis);
  319. while(true){
  320. System.out.println("read start....");
  321. ByteBuffer bb=ByteBuffer.allocate(200);
  322. boolean flag=client.readData(socketChannel, bb);
  323. byte[] b=new byte[bb.limit()];
  324. bb.get(b, 0, bb.limit()-1);
  325. System.out.println(new String(b,"UTF-8"));
  326. if(!flag){
  327. System.out.println("socket close....");
  328. client.closeSocketChannel(socketChannel);
  329. break;
  330. }
  331. }
  332. System.out.println("read data end....");
  333. System.exit(0);
  334. }
  335. }

http stream的更多相关文章

  1. SQL Server-聚焦查询计划Stream Aggregate VS Hash Match Aggregate(二十)

    前言 之前系列中在查询计划中一直出现Stream Aggregate,当时也只是做了基本了解,对于查询计划中出现的操作,我们都需要去详细研究下,只有这样才能对查询计划执行的每一步操作都了如指掌,所以才 ...

  2. Node.js:理解stream

    Stream在node.js中是一个抽象的接口,基于EventEmitter,也是一种Buffer的高级封装,用来处理流数据.流模块便是提供各种API让我们可以很简单的使用Stream. 流分为四种类 ...

  3. node中的Stream-Readable和Writeable解读

    在node中,只要涉及到文件IO的场景一般都会涉及到一个类-Stream.Stream是对IO设备的抽象表示,其在JAVA中也有涉及,主要体现在四个类-InputStream.Reader.Outpu ...

  4. nodejs中流(stream)的理解

    nodejs的fs模块并没有提供一个copy的方法,但我们可以很容易的实现一个,比如: var source = fs.readFileSync('/path/to/source', {encodin ...

  5. Node学习笔记(一):stream流操作

    NodeJs中谈及较多的可能就是Stream模块了,先写一个简单的ajax回调 $.post("index.php",{data:'aaa',order:'ccc'},functi ...

  6. Stream

    Stream的好处 1.Stream AP的引入弥补了JAVA函数式编程的缺陷.2.Stream相比集合类占用内存更小:集合类里的元素是存储在内存里的,Stream里的元素是在访问的时候才被计算出来. ...

  7. Stream流

    在Node中,存在各式各样不同的数据流,Stream(流)是一个由不同对象实现的抽象接口.例如请求HTTP服务器的request是一个 流,类似于stdout(标准输出):包括文件系统.HTTP 请求 ...

  8. [LeetCode] Data Stream as Disjoint Intervals 分离区间的数据流

    Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen ...

  9. [LeetCode] Moving Average from Data Stream 从数据流中移动平均值

    Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...

  10. [LeetCode] Find Median from Data Stream 找出数据流的中位数

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

随机推荐

  1. 你了解大O符号(big-O notation)么?你能给出不同数据结构的例子么?

    大O符号表示当数据结构的元素增加的时候,算法规模或者性能在最坏场景下有多好. 大O符号也可以用来描述其他行为,比如说内存消耗.因为集合实际上就是一种数据结构,我们一般用大O符号基于时间.性能.内存消耗 ...

  2. keil的可烧写hex文件生成

    右键Target1 Options Target for ‘Target1’ ...->Output->Create Executable:->Create HEX File Bui ...

  3. mail语法

    在Linux系统下mail命令的用法 在Linux系统下mail命令的测试 1. 最简单的一个例子: mail -s test admin@aispider.com 这条命令的结果是发一封标题为tes ...

  4. [转]Haproxy原理(1)

    本文出处:https://www.cnblogs.com/skyflask/p/6970151.html 目录 一.四层和七层负载均衡的区别二.HAProxy与LVS的异同三.快速安装HAProxy集 ...

  5. ckeditor_学习(1) 基本使用

    ckeditor 是一款强大的web编辑器.工作需要用到记录学习和使用过程,版本是ckeditor4. 1.下载ckeditor的安装包,建议下载标准版的. j将ckeditor.js 引入页面,调用 ...

  6. Spring history&Design Philosophy 简单介绍~

    SPRING框架的介绍和历史 Spring Framework是一个开源Java应用程序框架,最初是基于依赖注入(DI)和控制反转(IoC)的原理开发的. Spring Framework已经成长为控 ...

  7. Python基础:一、编程语言分类

    编程语言主要从以下几个角度进行分类: 编译型和解释型 静态语言和动态语言 强类型语言和弱类型语言 编译型语言和解释型语言 编译和解释的区别是什么? 编译器是把源程序的每一条语句都编译成机器语言,并保存 ...

  8. iso系统镜像刻录到光盘和U盘

    使用UltraISO刻录 刻录U盘,点击文件,打开,选择镜像 启动,写入硬盘镜像选择U盘即可 刻录光盘 工具,刻录光盘映像,选择镜像,需要先插入光盘刻录机(有些电脑可能自带光驱盘,且有刻录功能,那么我 ...

  9. day 44 JavaScript

    一.javascript简介 JavaScript是前台语言 JavaScript是前台语言,而不是后台语言. JavaScript运行在用户的终端网页上,而不是服务器上,所以我们称为“前台语言”.J ...

  10. Python调用ffpmeg和ffprobe处理视频文件

    需求: 运营有若干批次的视频.有上千个,视频文件,有mp4格式的,有ts格式的 现在有需要去掉视频文件片头和片尾的批量操作需求. 比如 文件夹A下面的视频去掉片尾10秒 文件夹B下面的视频去掉片头6秒 ...