http stream

http stream

博客分类:
    •  http://canofy.iteye.com/blog/2097876
 
Java代码   收藏代码
  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 当遇到这种空传输单元时结束 

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

转载于:https://www.cnblogs.com/nijb/p/7696025.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值