在java中通过套接字发送大文件时出错

时间:2016-01-11 12:30:35

标签: java serversocket socketexception

编辑:我在一个插槽中混合缓冲和非缓冲流。谢谢你的帮助

我正在编写P2P程序,在将文件发送到另一个IP时遇到问题,我正在

Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at Client.download(Client.java:315)
at Client.main(Client.java:37) 

在客户端,大约90%进入文件。

我认为它是因为服务器在客户端停止读取之前关闭了连接,但我尝试了睡眠并等待,这使得客户端只是挂起。

我很感激任何指出我所犯错误的反馈,谢谢!

服务器

String USER_NAME = System.getProperty("user.name");

DataOutputStream d_outToClient = new DataOutputStream(clientSocket.getOutputStream());

d_outToClient.writeBytes(fileName + '\n');
BufferedReader ok_inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedInputStream bis = null;
OutputStream os = null;
try {
    File file = new File("C:\\Users\\" + USER_NAME + "\\Downloads\\" + fileName);

    int count;
    byte[] bufor = new byte[8192];
    bis = new BufferedInputStream(new FileInputStream(file));
    os = clientSocket.getOutputStream();
    while ((count = bis.read(bufor)) > 0) {
        os.write(bufor, 0, count);
    }

    os.flush();
    System.out.println("sent");
} finally {
    if (bis != null)
        bis.close();
    if (os != null)
        os.close();
    if (clientSocket != null)
        clientSocket.close();
}

客户端:

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String response = inFromServer.readLine();
System.out.println(response);
outToServer.writeBytes("ok" + '\n');

String filePath = "C:\\Users\\" + USER_NAME + "\\Desktop\\" + response;

InputStream is = clientSocket.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int count;
byte[] bufor = new byte[8192];

while ((count = is.read(bufor)) > 0)// error in THIS line
{
    bos.write(bufor, 0, count);
    System.out.println("Downloading.....");
}

bos.flush();
System.out.println("Downloaded");
bos.close();
clientSocket.close();

0 个答案:

没有答案
相关问题