DataInputStream的使用,读阻塞

今天写了个程序,观看HTTP上传文件的流格式,发现:

DataInputSteam的 readFully(byte b[ ] )方法,当不能完全填充b[ ]时, 会阻塞程序的执行,直到读到足够的数据为止,

程序才继续执行下去!

代码:

 

import  java.io.BufferedReader;
import  java.io.DataInputStream;
import  java.io.DataOutputStream;
import  java.io.EOFException;
import  java.io.IOException;
import  java.io.InputStreamReader;
import  java.io.OutputStream;
import  java.net.ServerSocket;
import  java.net.Socket;

public   class  HttpServer  extends  Thread  {
    
private int SERVER_PORT=3221;
    
private ServerSocket s=null;
    
public HttpServer() throws IOException{
       
        s
=new ServerSocket(SERVER_PORT);
        
    
}

    
public HttpServer(int SERVER_PORT) throws IOException{
            
this.SERVER_PORT=SERVER_PORT;
            s
=new ServerSocket(SERVER_PORT);
            
        
    }

    
    
public void run(){
        
try {
            
            
while(true){
            Socket socket
=s.accept();
            System.out.println(
"响应客户端:"+System.currentTimeMillis());
            
new Answer2Client(socket).start();
            }

            
        }
 catch (IOException e) {
            System.out.println(
"HttpServer-->run()方法中出错");
            e.printStackTrace();
        }

        
    }

     
    
public static void main(String sssp[]) throws Exception{
        HttpServer server
=null;
        
if(sssp.length!=0)
            server
=new HttpServer(Integer.parseInt(sssp[0]));
        
else
           server
=new HttpServer();
        
        server.start();
    }

    
}

class  Answer2Client  extends  Thread {
    
private Socket client=null;
    
private byte[] b=new byte[10240];
    
public Answer2Client(Socket ss){
         
this.client=ss;
    }

    
    
    
public void run(){
        
try {
            BufferedReader  datain
=new BufferedReader(new InputStreamReader(client.getInputStream()));
            
while(true){
                
        
//    datain.readFully(b);
            String line=datain.readLine();
            
if(line==null)break;
                System.out.println(line);
            
            }
//while
            
            System.out.println(
"  结--------束");
            
        }
catch(IOException e) {
            System.out.print(
"  结束");
            e.printStackTrace();
        }

        
//响应
        
        DataOutputStream dataout;
        
try {
            dataout 
= new DataOutputStream(client.getOutputStream());
            String time
=System.currentTimeMillis()+" 时间time";
            dataout.writeChars(
""+time+"");
            dataout.flush();
            dataout.close();
            client.shutdownOutput();
            client.shutdownInput();    
            client.close();
    
            
        }
 catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

    
        
    }

}

程序不能正长结束,不知道怎么关闭套界字,和流

 

 

 

你可能感兴趣的:(历史难题+解决办法)