-1

Here is the problem i am working on. 1)There is one server and one client. 2)server is connected with client. 3)server sends one file(.mp3). 4)after sending the file it sends some additional String data.

I am getting IOException after the file is sent, so i client is not reading additional string data.WHYYYYYYYY?

Here is the server code

 public class server {

ServerSocket server;
Socket socket;
FileInputStream fis;
FileOutputStream fos;
DataInputStream dis;
DataOutputStream dos;

public static void main(String args[])
{       
    server s=new server();
    s.connnect();
    s.init();
    s.send("f://song.mp3");     
}

public void connnect()
{
    try {
        server=new ServerSocket(8080);
        socket =server.accept();
    } catch (IOException e) {

    }       
}

public void init()
{
    try {
        dis=new DataInputStream(socket.getInputStream());
        dos=new DataOutputStream(socket.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

public void send(String name)
{
    File f=new File(name);
    try {
        fis=new FileInputStream(f);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

    String nam=f.getName();

    try {
        dos.writeUTF(nam);
        System.out.println("header sent");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    byte[] buffer=new byte[1024];

    int read=-1;

    try {
        while((read=fis.read(buffer))!=-1)
        {
            dos.write(buffer, 0, read);
        }

        System.out.println("file "+name+" sent");

        dos.writeUTF("this is the msg which is not received by client because of IOexception in client side");

    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }               
}

}

Client side code

 public class client {


ServerSocket server;
Socket socket;
FileInputStream fis;
FileOutputStream fos;
DataInputStream dis;
DataOutputStream dos;

public static void main(String args[])
{
    client s=new client();
    s.connect();
    s.init();
    try {           
    s.rec(s.dis.readUTF());      ///this the name of the String         
    } catch (IOException e) {

    }       
}

public void connect()
{
    try {
        socket=new Socket("127.0.0.1",8080);
        System.out.println("connected with server");
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

public void init()
{
    try {
        dis=new DataInputStream(socket.getInputStream());
        dos=new DataOutputStream(socket.getOutputStream());
    } catch (IOException e) {
        System.out.println("IO EXception in streams");
        e.printStackTrace();
    }       
}

public void rec(String filename)
{
    File f=new File("f://abc");
    f.mkdirs();     
    File temp=new File(f,filename);     
    try {
        fos=new FileOutputStream(temp);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

    byte[] buffer=new byte[1024];
    int read=-1;

    System.out.println("started reading file"+filename);

    try {           
        while((read=dis.read(buffer))!=-1)
        {
            fos.write(buffer, 0, read);
        }

        String FINAL_MSG=dis.readUTF();
        System.out.println("ended "+FINAL_MSG);

    } 
    catch (IOException e) {
        System.out.println("why IO exception?");
    }       
}

public void sendFile(String name)
{
    File f=new File("f://abc");
    f.mkdirs();

    File temp=new File(f,name);

    try {
        fos=new FileOutputStream(temp);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    byte[] buffer=new byte[1024];
    int read=-1;

    try {
        while((read=dis.read(buffer))!=-1)
        {
            fos.write(buffer, 0, read);
        }
    } 
    catch(SocketException e)
    {
        System.out.println(name+" has end"+" "+(socket==null));

    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}   

}

I want to read the additional string data (FINAL_MSG). how it is possible?

Server output

header sent     
file f://song.mp3 sent       
Final MSG is sent from server side 

Client output

connected with server    
started reading filesong.mp3     

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.DataOutputStream.write(Unknown Source)
at s1.send(s1.java:87) at s1.main(s1.java:30)

why IO exception?

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
  • 1
    Add the full stacktrace of the IOException. – Thorbjørn Ravn Andersen Mar 10 '16 at 20:08
  • no, my question is why does it go to catch(IOException){System.out.println("why IO exception"}. – Rohit Singh Mar 10 '16 at 20:12
  • @flkes it is .mp3 file it does gives -1 at the end of file. – Rohit Singh Mar 10 '16 at 20:14
  • @ThorbjørnRavnAndersen there you go 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.DataOutputStream.write(Unknown Source) at s1.send(s1.java:87) at s1.main(s1.java:30) – Rohit Singh Mar 10 '16 at 20:22
  • 1
    Your problem is very likely that the client code that reads the "file data" also ends up reading your final message and save it to the file. So when you are trying to read the final message in the client, you are now "end of stream". – Quintium Mar 10 '16 at 20:36
  • The exception should have been posted in your question. You can see for yourself that t is illegible in a comment. I fixed it for you. I also removed about a hundred yards of pointless vertical white space. Don't waste it, especially here. It's just more illegibility. – user207421 Mar 10 '16 at 20:45
  • @Quintium . is it so? how can i seperate it? – Rohit Singh Mar 10 '16 at 20:53
  • 1
    As @Quintium said you are consuming the entire stream. You need to send a control over to set the length. Send a long value that you read on the other side so you end up only reading the portion that is the file. Then finish the rest of the stream as a string. – markbernard Mar 10 '16 at 21:08
  • @RohitSingh Get rid of the final message. You don't need it. Just closing the socket is sufficient. – user207421 Mar 10 '16 at 21:08
  • As @markbernard wrote, it is suggested to send a length header (usually of a 2 to 4 bytes) than contains the length (be careful of byte order, it can depend on systems.) Read the 2 to 4 bytes first, then read from the buffer up to that length and that should be your mp3 file. If you need other messages, delimiter them all with length headers. – Quintium Mar 11 '16 at 15:11
  • yes its working now :) – Rohit Singh Mar 11 '16 at 16:07

2 Answers2

2

Your Server program is terminated before client could read all data resulting into IO Exception.

Your Server program is sending a mp3 file, then printing message file sent, again writing data over the socket and then since nothing is left to do, it is terminated/ends so server socket is closed, which in turn causes IO Exception in the client program.

Sumit Rathi
  • 693
  • 8
  • 15
  • getting IOException at client side – Rohit Singh Mar 10 '16 at 20:25
  • That is what I mentioned in my answer since the server is gone u are getting IO Exception in client side/ client program. This is how TCP works. Your Server program is ending . I have run your code my self. If you want to verify what I am saying, Why don't you put a breakpoint in the client program where you are getting exception. You will see when hit exception in client side at that point of time server side is not running. – Sumit Rathi Mar 10 '16 at 20:26
  • I am getting exception between while ((read=dis.read(buffer))!=-1) { fos.write(buffer, 0, read); } and FINAL_MSG = dis.readUTF(); – Rohit Singh Mar 10 '16 at 20:40
  • @SumitRathi There is zero evidence that the server is ending. All we know is that it has closed the connection. – user207421 Mar 10 '16 at 20:41
  • reconnecting does not make sense to me. for sending every file – Rohit Singh Mar 10 '16 at 20:41
  • @EJP if you will run the program mentioned in question, You will get proof. I added few sysouts having timestamps in his program to verify it. – Sumit Rathi Mar 10 '16 at 20:45
  • @RohitSingh , You don't have to reconnect. You need to add a mechanism / add a application level protocol so that server waits untill client recieves all data. – Sumit Rathi Mar 10 '16 at 20:49
  • 1
    @RohitSingh : Please add following lines in Scanner sc = new Scanner(System.in); String end = sc.next(); main method of server program after calling send method. You will notice that you will not get any IO Exception after adding these lines, because now server is waiting for some input. By this way, you would be able to verify what I have mentioned in my answer that your server program ends before client could read all data. After verifying do convert -1 to +1 :) – Sumit Rathi Mar 10 '16 at 21:01
  • yes. the error is gone – Rohit Singh Mar 10 '16 at 21:16
  • @SumitRathi , does it mean the FINAL_MSG is added the byte oriented data of .mp3? – Rohit Singh Mar 10 '16 at 21:17
  • Yes most likely. Since you have verified my answer , I would really appreciate if you remove downvote from my answer, and if you think it is correct then mark it as correct. – Sumit Rathi Mar 10 '16 at 21:25
0

The peer has already closed the connection while you are still writing to it. In other words, an application protocol error.

In this case the server isn't closing the accepted socket but is just exiting the thread.

user207421
  • 305,947
  • 44
  • 307
  • 483