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. mybatis foreach 遍历list中的坑

    将jdbc改写为mybatis时,传入的条件为list使用到的标签是<where> .<choose>.<when>.<if>.<foreach& ...

  2. java中求余%与取模floorMod的区别

    初学java的时候接触的%这个符号 百分号? 求余? 取模? 我只知道不是百分号,好像是求余,听别人那叫求模运算符,跟求余一样,于是我便信了. 思考之后开始迷糊,然后经过多次考证得到以下结论. 首先, ...

  3. 2017年3月30日15:00:19 fq以后的以后 动态代理

    代理与继承,组合不同的是,继承是继承父类特性,组合是拼装组合类的特性,代理是使用代理类的指定方法并可以做自定义. 静态类是应用单个类,当代理的类数量较多时可用动态代理,动态代理在概念上很好理解 htt ...

  4. 由一次报错引发的对于Spring创建对象的理解

    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ent ...

  5. Python pip源更改

    将pip源设置为阿里源 windows 打开文件资源管理器(文件夹地址中) 地址栏上面输入 %appdata% 在这里面新建一个文件夹pip 在pip文件夹里面新建一个文件叫做 pip.ini,内容如 ...

  6. python学习之路03

    一.常量和变量 1.python中的数据类型 分类: ​ Number:数字型[整型,浮点型,复数] ​ String:字符串型 ​ Boolean:布尔型[True,False] ​ None:空值 ...

  7. Js高级 部分内容 面向对象

    1.单列模式 2.工厂模式 3.构造函数 (1)类 js天生自带的类 Object基类 Function  Array  String  Number  Math Date Boolean Regex ...

  8. I think I need a boat house

    I think I need a boat house. Fred Mapper is considering purchasing some land in Louisiana to build h ...

  9. 在html中做表格以及给表格设置高宽字体居中和表格线的粗细

    今天学习了如何用HTML在网页上做表格,对于我这种横列部分的属实有点麻烦,不过在看着表格合并单过格的时候我把整个表格看做代码就容易多了. 对于今天的作业让我学习了更多的代码,对于代码的应用希望更加熟练 ...

  10. 《DSP using MATLAB》Problem 7.3