http stream

时间:2023-03-09 03:22:54
http stream

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. }