-1

I am trying to code a java socket server to send an image from this server to the navigator(client side). But when I send the image the file seen to be corrupted (display the image with symbols).

                DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
                String file="image.jpg";
                File filename = new File(file);
                FileInputStream fin = new FileInputStream(filename);  
                //dout.writeUTF(file);
                System.out.println("Sending image...");
                int size=(int) filename.length();
                byte[] readData = new byte[size]; 
                fin.read(readData);
                dout.writeInt(size);
                dout.flush();
                dout.write(readData,0,size);
                /*for(int i=0;i<readData.length;i++) {
                     dout.write(readData, 0, i);
                }*/
                dout.flush();

Here is how I start the program

    ServerSocket ss=new ServerSocket(8080);
    Socket connectS=ss.accept();
    BufferedReader in=new BufferedReader(new InputStreamReader(connectS.getInputStream()));

Thanks for your help!!!

daiboss
  • 7
  • 2
  • Instead of DataOutputStream try using the OutputStream directly to write your file. DataOutputStream writes formatted binary data while OutputsStream writes the raw data. – Thecarisma Apr 08 '20 at 10:39
  • I changed to OutputStream dout=new DataOutputStream(connectS...) but it doesn't change anything. I can't change the second DataOutputStream whithout having an error. – daiboss Apr 08 '20 at 16:33
  • 1
    Why are you sending the size word? Why aren't you sending any HTTP headers? – user207421 Apr 08 '20 at 21:08
  • @Thecarisma `DataOutputStream` doesn't change what is written. Your suggestion makes no difference, or sense. – user207421 Apr 08 '20 at 21:26
  • Oh my bad, I read the question wrong – Thecarisma Apr 08 '20 at 22:18

1 Answers1

-1

I solved the problem. First, remove dout.readInt(); Then, open microsoft edge;(mozilla shows the image but there seems to be an encoding issue,that's my opinion,maybe not the true);

daiboss
  • 7
  • 2