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. 8.6 C++文本文件的读写操作

    参考:http://www.weixueyuan.net/view/6412.html 总结: 文件类型: 计算机上的文件其实是数据的集合,对文件的读写归根结底还是对数据的读写操作.文件可以大致分为两 ...

  2. SQL JOIN语法,以及JOIN where 和and区别,还有where和join效率问题。

    语法 join 用于根据两个或多个表中的列之间的关系,从这些表中查询数据. Join 和 Key 有时为了得到完整的结果,我们需要从两个或更多的表中获取结果.我们就需要执行 join. 数据库中的表可 ...

  3. MFC VC++ 根据文件名获取程序的Pid

    环境:PC Win7 VS VC++ .MFC 使用,输入文件名即可获取程序的pid,进而可以对程序进行操作,比如关闭Porcess等. 头文件: #include <TlHelp32.h> ...

  4. flex 1与flex auto

    flex意为"弹性布局" 这次主要探究的是flex:1与flex:auto的区别,flex是flex-grow, flex-shrink 和 flex-basis的简写,默认值为0 ...

  5. java学习笔记38(sql注入攻击及解决方法)

    上一篇我们写了jdbc工具类:JDBCUtils ,在这里我们使用该工具类来连接数据库, 在之前我们使用 Statement接口下的executeQuery(sql)方法来执行搜索语句,但是这个接口并 ...

  6. python中Requests库错误和异常

    主要有以下四种: 1.Requests抛出一个ConnectionError异常,原因为网络问题(如DNS查询失败.拒接连接等错误) 2.Response.raise_for_status()抛出一个 ...

  7. [转] Ubuntu16.04完美安装Sublime text3

    转载自:https://www.cnblogs.com/hupeng1234/p/6957623.html 1.安装方法 1)使用ppa安装 sudo add-apt-repository ppa:w ...

  8. Python 实现简易 Shell

    什么是shell? (1)shell是一个系统软件,负责用户和操作系统内核之间的交互,是产生进程的进程(通过linux系统调用fork,exec),主要负责解释用户的命令,进而实现用户对进程的控制. ...

  9. 3.6 html报告乱码问题优化

    3.6 html报告乱码问题优化 前言python2用HTMLTestRunner生成测试报告时,有中文输出情况会出现乱码,这个主要是编码格式不统一,改下编码格式就行.下载地址:http://tung ...

  10. controller向layout传值

    Yii2,layout中使用Controller的值,Controller向layout传值的两种方式. yii2中在通过Controller向layout中传值,layout中访问Controlle ...