现在我有客户端和服务端两个程序,
客户端发送文件给服务端代码如下:发送:public void SendFile(String fileType,String filePath,Socket socketHandler) throws IOException
{

DataInputStream fileInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream fileOutStream = new DataOutputStream(socketHandler.getOutputStream());

int bufferSize = 8192;   
byte[] buf = new byte[bufferSize];   

while (true)
{
int read=0;
if(fileInputStream!=null)
{
read=fileInputStream.read(buf);
}

if(read==-1)
{
break;
}
fileOutStream.write(buf, 0, read);
}

fileOutStream.flush();
fileInputStream.close();
//socketHandler.close();
接收:public void ReceiveFile(String fileSavePath,Socket socketHandler,String fileType,String fileName, int fileLength,boolean isUpload) throws IOException
{

String filePureName="";
long len=0;
int bufferSize = 8192;  
byte[] buf = new byte[bufferSize];    

   if(fileName.lastIndexOf("\\")>0)
{
filePureName=fileName.substring(fileName.lastIndexOf("\\")+1);
}
else if(fileName.lastIndexOf("/")>0)
{
filePureName=fileName.substring(fileName.lastIndexOf("/")+1);
}
else
{
filePureName=fileName;
}
fileSavePath+=filePureName;
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(fileSavePath))));  
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socketHandler.getInputStream())); 

while (true)
{
int read=0;
if (inputStream!= null) 
{   
read = inputStream.read(buf); 
}

len+=read;
fileOut.write(buf, 0, read);

if (read == -1 || fileLength==len) { 
break;   
}
}

fileOut.flush();
fileOut.close();
}
现在情况是这样的,一般来说发送端第一次链接服务端的时候,可以正常接收文件,但是第二次就会死锁刀:
接收方法里面 的  read = inputStream.read(buf);这句话中我看网上有很多是说发送端要close socket,但是我close 发送端的socket后,接收端read = inputStream.read(buf);这句话就读不出东西了,read 始终等于-1请高手指点下。

解决方案 »

  1.   


    不行啊大哥,我加了,还是第一次可以通过,第二次就卡在了
    read = inputStream.read(buf); 这句话上了
      

  2.   

    另外补充点,我每次上传一次文件后,都要关闭socket.第二次需要再次连接socket,然后在发送文件。
      

  3.   


    您能不能告诉我怎么建一个新会话呢?逻辑我觉得不会有问题吧,因为如果客户端和服务端交互简单的字符串一类的东西,完全没有问题,只有传文件有问题。只能传一次。。第二次就死锁。。我每次交互完(每发一个命令,到命令结束)服务端和客户端的 socket都关闭。
      

  4.   

    socket是一读一写...............没有只读不写的,客服端发起请求,服务器要响应,没有只读不写的说法
      

  5.   


    if(read == -1 || fileLength==len){ break;}
    改为:
    if(read != -1){
           read = inputStream.read(buf); 
    }else{
           break;
    }
    if(fileLength != len){
           continue;
    }else{
          break;
    }
      

  6.   

    完整的是这样:    while(true){
            int read=0;
            if(read != -1){
                  read = inputStream.read(buf); 
            }else{
                  break;
            }
            len+=read;
            fileOut.write(buf, 0, read);
            if(fileLength != len){
                  continue;
            }else{
                  break;
            }    }