http stream

阅读更多
StringBuilder sb = new StringBuilder();   
sb.append("HTTP/1.1 200 OK\r\n");   
sb.append("Content-Type: text/plain\r\n");   
sb.append("Transfer-Encoding: chunked\r\n\r\n");   
sb.append("25\r\n");           
sb.append("This is the data in the first chunk\r\n"); // 37 bytes   
sb.append("\r\n1A\r\n");   
sb.append("and this is the second one"); // 26 bytes   
sb.append("\r\n0\r\n\r\n");  


十六进制包长+\r\n+报文包+\r\n  为一个传输单元

0+\r\n+\r\n 当遇到这种空传输单元时结束

下面是客户端例子

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;



public class Client {
	public boolean isAsync=false;
	
	
	/**
	 * 建立socket
	 * @param ip
	 * @param port
	 * @return
	 * @throws IOException 
	 * @throws NumberFormatException 
	 * @throws PachiraAsrSocketCreateException
	 */
	protected SocketChannel createSocketChannel(String ip,String port) throws NumberFormatException, IOException {
		SocketChannel socketChannel=null;
			if(isAsync){
				 socketChannel = SocketChannel.open();  
				 socketChannel.configureBlocking(false);  
		        //向服务端发起连接  
		        if (!socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)))){  
		            //不断地轮询连接状态,直到完成连接  
		            while (!socketChannel.finishConnect()){  
		                //在等待连接的时间里,可以执行其他任务,以充分发挥非阻塞IO的异步特性  
		                //这里为了演示该方法的使用,只是一直打印"."  
		            	try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
						}
//		                SrvLogger.debug(getClass(), "");  
		            }  
		        }
			}else{
				socketChannel = SocketChannel.open();
				socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)));
			}
		
		return socketChannel;
	}
	
	
	/**
	 * 关闭socket
	 * @param socketChannel
	 * @param uuid
	 * @throws IOException 
	 */
	protected void closeSocketChannel(SocketChannel socketChannel) throws IOException{
		if(socketChannel!=null){
			socketChannel.close();
		}
	}
	/**
	 * 传输数据
	 * @param socket
	 * @param in
	 * @param uuid
	 * @param audioType
	 * @throws IOException 
	 */
	protected boolean sendStringData(final SocketChannel socketChannel ,final String str) throws IOException{
		ByteBuffer buffer=ByteBuffer.wrap(str.getBytes(), 0, str.length());
		int size=0;
		int wl=0;
		System.out.println("buf.limit="+buffer.limit());
		wl=socketChannel.write(buffer);
		while (buffer.hasRemaining()) {
			if (wl < 0){ 
		        System.out.println("sendData len is -1;size="+size);
		        break;
		    } 
			if (wl == 0) {
				System.out.println("sendData len is 0 ;size="+size);
			}
			size+=wl;
			
		}
		
		buffer.flip();
		
		return true;
	}
	
	
	/**
	 * 传输数据
	 * @param socket
	 * @param in
	 * @param uuid
	 * @param audioType
	 */
	protected boolean sendData(final SocketChannel socketChannel ,final InputStream is){
		FutureTask task  = new FutureTask(new Callable(){  
		    public Integer call() {
		    		System.out.println("sendData start...;");
		    		byte[] buf = new byte[8096];
		    		int totalSize=0;
		    		int sendTotalSize=0;
		    		try {
		    			int read = is.read(buf, 0, buf.length);
		    			while (read > 0) {
		    				totalSize+=read;
	    					ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
    						int size=0;
    						int wl=0;
    						wl=socketChannel.write(buffer);
		    				while (buffer.hasRemaining()) {
		    					if (wl < 0){ 
	    					        System.out.println("sendData len is -1;size="+size);
	    					        break;
	    					    } 
		    					if (wl == 0) {
		    						System.out.println("sendData len is 0 ;size="+size);
		    					}
		    					size+=wl;
		    					
		    				}
		    				
		    				buffer.flip();
		    				sendTotalSize+=read;
		    				read = is.read(buf, 0, buf.length);
		    			}
		    			sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
		    			System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
		    		}catch (Exception e) {
		    			e.printStackTrace();
		    		}finally{
		    			
		    		}
		    		
		    		
		    	return new Integer(8); 
		    }
		});
		ExecutorService sendDataPool=Executors.newCachedThreadPool();
		sendDataPool.execute(task);
		return true;
		
	}
	
	
	/**
	 * 传输数据
	 * 十六进制包长+\r\n+报文包+\r\n  为一个传输单元

		0+\r\n+\r\n 当遇到这种空传输单元时结束
	 * @param socket
	 * @param in
	 * @param uuid
	 * @param audioType
	 */
	protected boolean sendDataChunk(final SocketChannel socketChannel ,final InputStream is){
		FutureTask task  = new FutureTask(new Callable(){  
		    public Integer call() throws IOException {
		    		System.out.println("sendData start...;");
		    		sendStringData(socketChannel, "\r\n");
		    		String parameter="------------V2ymHFg03ehbqgZCaKO6jy\r\nContent-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";\r\n\r\n";
		    		sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
		    		sendStringData(socketChannel, parameter+"\r\n");
//		    		sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
//		    		sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
//		    		sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
//		    		sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
//		    		sendStringData(socketChannel, Integer.toHexString("------------V2ymHFg03ehbqgZCaKO6jy".length())+"\r\n");
//		    		sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy\r\n");
//		    		String parameter="Content-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";";
//		    		sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
//		    		sendStringData(socketChannel, parameter+"\r\n");
		    		
		    		byte[] buf = new byte[8096];
		    		int totalSize=0;
		    		int sendTotalSize=0;
		    		try {
		    			int read = is.read(buf, 0, buf.length);
		    			while (read > 0) {
		    				
		    				totalSize+=read;
	    					ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
	    					
	    					String hex= Integer.toHexString(read);
	    					System.out.println("read="+read+";hex="+hex);
	    					sendStringData(socketChannel,hex+"\r\n");
    						int size=0;
    						int wl=0;
//    						System.out.println("send..");
    						wl=socketChannel.write(buffer);
//    						System.out.println("send...");
		    				while (buffer.hasRemaining()) {
		    					if (wl < 0){ 
	    					        System.out.println("sendData len is -1;size="+size);
	    					        break;
	    					    } 
		    					if (wl == 0) {
		    						System.out.println("sendData len is 0 ;size="+size);
		    					}
		    					size+=wl;
		    					
		    				}
		    				sendStringData(socketChannel, "\r\n");
		    				buffer.flip();
		    				sendTotalSize+=read;
		    				read = is.read(buf, 0, buf.length);
		    				Thread.sleep(50);
		    			}
		    			sendStringData(socketChannel, Integer.toHexString("------------V2ynHFg03ehbqgZCaKO6jy--".length())+"\r\n");
		    			sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
		    			sendStringData(socketChannel, "\r\n");
		    			sendStringData(socketChannel, "0\r\n\r\n");
		    			System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
		    		}catch (Exception e) {
		    			e.printStackTrace();
		    		}finally{
		    			
		    		}
		    		
		    		
		    	return new Integer(8); 
		    }
		});
		ExecutorService sendDataPool=Executors.newCachedThreadPool();
		sendDataPool.execute(task);
		return true;
		
	}
	
	/**
	 * 读取
	 * @param inputStream
	 * @param buf
	 * @return
	 * @throws IOException
	 */
	protected boolean readData(SocketChannel socketChannel, ByteBuffer buf) {
		boolean ret = true;
		long count=0;
		try {
			count = socketChannel.read(buf);
//			if(this.isAsync){
				while(count 

你可能感兴趣的:(http stream)