使用BufferedInputStream读取文件时出现SocketException

时间:2017-02-20 05:30:36

标签: sockets streaming

我正在编写TCP服务器和客户端,客户端将在其中发送文件,服务器将保存该文件。我的发送/保存功能如下:

服务器

public void saveFile2(Socket clientSocket) throws IOException
{
    BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
    DataInputStream dis = new DataInputStream(bis); 
    String fileName = dis.readUTF();        
    File file = new File(fileName); 
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);               
    int byteCount;
    byte[] buffer = new byte[4096];
    while ((byteCount = bis.read(buffer, 0, buffer.length)) > 0)
    {
        System.out.println("Test byteCount = "+byteCount);
        bos.write(buffer, 0, byteCount); 
        break;
    }
    System.out.println("Saved file"+file.getName());
    bos.close();
    dis.close();
}

客户端

public void sendFile2(String xmlpath) throws IOException, InterruptedException
{
    BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
    DataOutputStream dos = new DataOutputStream(bos);
    File file = new File(xmlpath);
    System.out.println("Sending File : " + file.getName());
    dos.writeUTF(file.getName());
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    int bytesCount;
    byte[] buffer = new byte[4096];
    System.out.println("Sending file to server.");
    while ((bytesCount = fis.read(buffer)) > 0 )
    {
        System.out.println(bytesCount);
        bos.write(buffer, 0, bytesCount);
    }
    System.out.println("Finished sending.");

    bis.close();
    dos.flush();
}

请注意我添加了休息时间;命令进入Server的while循环,程序运行完美。但是当我排除它时,我得到了这个例外:

Test byteCount = 394
java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:209)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
        at xml.xmlServer.saveFile2(xmlServer.java:72)
        at xml.xmlServer.run(xmlServer.java:31)

只有在我的代码中包含BufferedInputStream和BufferedOutputStream时才会出现这种情况。有人可以帮我解释导致这种异常的原因吗?

1 个答案:

答案 0 :(得分:0)

您正在读取文件名,但您没有发送文件名。您在发件人中错过了writeUTF()来电。

您还需要关闭发件人或DataOutputStream

中的套接字
bos.write(buffer, 0, bytesCount);

真的应该是

dos.write(buffer, 0, bytesCount);