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. top 常用

    top -c 查看进程 同时 shift +m 内存倒序

  2. constructor&object 的对比

    Constructor vs object A constructor is a special member function in the class to allocate memory to ...

  3. xslfo和fop使用中的一些问题

    最近项目中使用fop和xslfo打印pdf,遇到一些问题记录下来: 1.表格跨行.跨列: 使用number-rows-spanned和number-columns-spanned属性 比如:<f ...

  4. 获取Ueditor里面的图片列表,地址绝对化

    /**     * 内容中图片地址转成绝对地址     * @param $content     * @return mixed     */    private function imgUrl( ...

  5. 分布式队列celery 异步----Django框架中的使用

    仅仅是个人学习的过程,发现有问题欢迎留言 一.celery 介绍 celery是一种功能完备的即插即用的任务对列 celery适用异步处理问题,比如上传邮件.上传文件.图像处理等比较耗时的事情 异步执 ...

  6. 重开Vue2.0

    目录: 内容: 一.Vue内部指令: 1.v-if v-else&v-show v-if与v-show都是选择性显示内容的指令,但是二者之间有区别: 1.v-if:判断是否加载,在需要的时候加 ...

  7. WEBBASE篇: 第五篇, CSS知识3

    CSS知识3 框模型: 一,外边距(上文) 二, 内边距    1,什么是内边距? 内边距就是内容与元素边缘之间的距离: 注: 内边距会扩大元素边框内所占的区域的 语法: padding: 四个方向的 ...

  8. SQL 优化经历

    一次非常有趣的 SQL 优化经历   阅读本文大概需要 6 分钟. 前言 在网上刷到一篇数据库优化的文章,自己也来研究一波. 场景 数据库版本:5.7.25 ,运行在虚拟机中. 课程表 #课程表 cr ...

  9. Concordion test

    reference documents http://concordion.org/Example.html

  10. C++学习(三十五)(C语言部分)之 单链表

    单链表 就好比火车 火车头-->链表头部火车尾-->链表尾部火车厢-->链表的节点火车厢连接的部分-->指针火车中的内容-->链表节点的的数据链表节点包含数据域和指针域数 ...