3

EDIT: I was mixing buffered and unbuffered streams in one socket. Thanks for help

I am writing P2P program and I run into problem while sending file to another IP, I am getting

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) 

on the client side, about 90% into the file.

I think its because server closes connection before client stops reading, but I tried sleep and wait and that leaves the client side just hanging.

I would appreciate any feedback pointing to the mistake I am making, thank you!

SERVER:

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();
}

CLIENT:

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();
Mags
  • 31
  • 3
  • 1
    "`java.net.Socket.Exception Connection reset`" I do not believe that is the correct text of the exception message. Post the correct text. – Raedwald Jan 11 '16 at 12:40
  • 1
    See http://stackoverflow.com/questions/839314/clientabortexception-java-net-socketexception-connection-reset-by-peer-socket – Raedwald Jan 11 '16 at 12:43
  • 1
    See http://stackoverflow.com/questions/1434451/what-does-connection-reset-by-peer-mean – Raedwald Jan 11 '16 at 12:44
  • 2
    Don't use comments to clarify your question. Edit your question to make it clearer. – Raedwald Jan 11 '16 at 13:07

0 Answers0