简体   繁体   中英

Why is my client closing the connection

Hi i am trying to learn how to send files through sockets so i coded two very simple java classes, client and server, here they are

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    public static void main (String[] args)throws IOException{
        File f = new File("J:\\RepServer\\zebi.txt");
        if(!f.exists()){
            f.createNewFile();
            }
        //System.out.print(f.exists()+f.getName());
        ServerSocket ss = new ServerSocket(1000);
        Socket s = ss.accept();
        FileInputStream fileStream = new FileInputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
        oos.writeObject("Envoi Fichier|"+f.getName()+"|"+f.length());
        byte[] buffer = new byte[150000];
        long completed =0;
        while(completed <= f.length()){
            fileStream.read(buffer);
            oos.write(buffer);
            completed += 150000;
        }
        oos.writeObject("Envoi termine");
        fileStream.close();
    }
}

and the client class

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;


public class Client {

/**
 * @param args
 * @throws ClassNotFoundException 
 */
public static void main(String[] args) throws IOException, ClassNotFoundException {
    new File("J:\\RepClient\\").mkdir();
    Socket s = new Socket("127.0.0.1",1000);
    ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
    String fileName = ((String)ois.readObject()).split("|")[1].trim();
    FileOutputStream fos = new FileOutputStream("J:\\RepClient\\"+fileName);
    byte[] buffer = new byte[200000];
    int byteLus = 0, compteur = 0;
    while(byteLus >= 0){
        byteLus = ois.read();
        if(byteLus >= 0){
            fos.write(buffer, 0, byteLus);
            compteur += byteLus;
            System.out.println("Le nombre de bytes lus est :"+byteLus);
        }
        if(byteLus < 1024){
            fos.flush();
            break;
        }
    }
}

}

So i start the server and then the client, the server sends the file to the client and the client create the file but empty, because before the server can write in it this exception occurs.

Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.writeBlockHeader(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream.write(Unknown Source)
at Server.main(Server.java:25)

The thing is i didn't close any socket or stream in the client. So why is the connection closed ? And btw what is flush doing ?

I think that the problem is in the way that you are trying to read data on the client side.

    byteLus = ois.read();

The read() method reads a single byte of data! Reference: the javadoc . But you seem to be assuming that it will (somehow) read a number of bytes into buffer . (Or something. The code is so wrong, it is not obvious what you think it should be doing!)


But frankly, there are lots of other problems with your code, both on the client and the server size. Some of the problems are as follows:

  • You should (probably) not be using read() or write(buffer) on an ObjectStream . You should be using readObject() and writeObject(obj) ... or using DataInputStream / DataOutputStream .

  • The way you are reading the file on the server side is broken. You are ignoring the result of the read call ... that tells you how many bytes you actually read into buffer . (You cannot assume that the only time you will get less that a full buffer is when you are near the end of the file. Some file types will regularly give you incomplete reads ... at least on some platforms.)

  • You are not closing oos or fos so there may be problems with data not being flushed.

  • The byteLus < 1024 test is inexplicable ... and wrong.

  • The logic of creating an empty file on the server if the file doesn't exist, escapes me (too). Why???

Your client exited when it got to end of stream, and exiting the process closes the socket. Meanwhile your server was still sending, because your sending and receiving code is completely up the pole. There are numerous other problems with your code as noted by @StephenC. The correct way to copy streams in Java is as follows:

while ((count = in.read(buffer)) > 0)
{
   out.write(buffer, 0, count);
}

Works with any size buffer > 0. Same code at both ends, with different inputs and outputs. Syntactic variations permissible: semantic variations not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM