1

I am working on a swing application on client/server program for sending different types of files via java sockets. I have used the following link for reference: File Transfer in Java

I have modified the code as per my requirements as below:

public File file;
public String fileName=new String();
String path=new String();

Server Side Code:

  try
    {
        File file=new File(path);
        ServerSocket servsock = new ServerSocket(12345);
        Socket sockFileName=servsock.accept();
        FileOutputStream fout=new FileOutputStream(path);           
        DataOutputStream dOut=new DataOutputStream(sockFileName.getOutputStream());
        dOut.writeUTF(fileName);
        dOut.flush();
        dOut.close();
        sockFileName.close();
        servsock.close();       
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(mainPanel, "file name: "+e);
        }
    try
    {
        ServerSocket servsock=new ServerSocket(12345);
        Socket sock = servsock.accept();
            byte[] mybytearray = new byte[(int) file.length()];
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            bis.read(mybytearray, 0, mybytearray.length);
            OutputStream os = sock.getOutputStream();
            os.write(mybytearray, 0, mybytearray.length);
            os.flush();
            os.close();
            sock.close();
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(mainPanel, "file sending: "+e);
        }

Client Side Code:

    try
    {            
        Socket sock = new Socket("127.0.0.1", 12345);         
        DataInputStream dIn=new DataInputStream(sock.getInputStream());
        fileName=dIn.readUTF();
        jLabel3.setText(fileName);
        dIn.close();
        sock.close();
    }
    catch(Exception e)
    {
       JOptionPane.showMessageDialog(mainPanel, "file name: "+e);
    }
           JOptionPane.showMessageDialog(mainPanel, "file is being recieved . . . ");
    try
    { 
        Socket sock = new Socket("127.0.0.1", 12345);
        byte[] mybytearray = new byte[1024];
        System.out.println("1");
        InputStream is = sock.getInputStream();
        System.out.println("2");
        File recievedFile=new File("Z:\\"+fileName);
        System.out.println("3");
        recievedFile.createNewFile();
        System.out.println("4");           
        FileOutputStream fos = new FileOutputStream(recievedFile);
        System.out.println("5");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        System.out.println("6");
        int bytesRead = is.read(mybytearray, 0, mybytearray.length);
        System.out.println("7");
        bos.write(mybytearray, 0, bytesRead);
        System.out.println("8");
        bos.flush();
        System.out.println("9");
        bos.close();
        sock.close();  
    }
    catch(Exception e)
    {
       JOptionPane.showMessageDialog(mainPanel, "file sending: "+e);
    }

I am really unable to troubleshoot why I am getting an ArrayOutOfBoundException on bos.write(mybytearray, 0, bytesRead); line of the client side while he receives the file.

Edit:

The code is a bit a complex structure, but I bet you will be able to find the functions. Actually the client and the server are both implemented on the same window using different buttons.

package samplefilesendrecieveclientserver;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.jws.WebService;
import javax.net.ssl.SSLServerSocket;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class SampleFileSendRecieveClientServerView extends FrameView {

    public SampleFileSendRecieveClientServerView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = SampleFileSendRecieveClientServerApp.getApplication().getMainFrame();
            aboutBox = new SampleFileSendRecieveClientServerAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        SampleFileSendRecieveClientServerApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(samplefilesendrecieveclientserver.SampleFileSendRecieveClientServerApp.class).getContext().getResourceMap(SampleFileSendRecieveClientServerView.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton2MousePressed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton3MousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton3MouseReleased(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(84, 84, 84)
                        .addComponent(jButton1))
                    .addComponent(jLabel1))
                .addContainerGap(96, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addGap(43, 43, 43))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(samplefilesendrecieveclientserver.SampleFileSendRecieveClientServerApp.class).getContext().getActionMap(SampleFileSendRecieveClientServerView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>                        
public File file;
public String fileName=new String();
String path=new String();
    private void jButton2MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:

        JFileChooser chooser=new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooser.showSaveDialog(null);

        path=chooser.getSelectedFile().getAbsolutePath();
        fileName=chooser.getSelectedFile().getName();
        jLabel1.setText(path);
        file=new File(path);



    }                                     

    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:

        try
        {
            File file=new File(path);
            ServerSocket servsock = new ServerSocket(12345);
            Socket sockFileName=servsock.accept();
            FileOutputStream fout=new FileOutputStream(path);           
            DataOutputStream dOut=new DataOutputStream(sockFileName.getOutputStream());
            dOut.writeUTF(fileName);
            dOut.flush();
            dOut.close();
            sockFileName.close();
            servsock.close();       
            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(mainPanel, "file name: "+e);
            }
        try
        {
            ServerSocket servsock=new ServerSocket(12345);
            Socket sock = servsock.accept();
                byte[] mybytearray = new byte[(int) file.length()];
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                bis.read(mybytearray, 0, mybytearray.length);
                OutputStream os = sock.getOutputStream();
                os.write(mybytearray, 0, mybytearray.length);
                os.flush();
                os.close();
                sock.close();
            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(mainPanel, "file sending: "+e);
            }

    }                                     

    private void jButton3MouseReleased(java.awt.event.MouseEvent evt) {                                       
        // TODO add your handling code here:

    }                                      

    private void jButton3MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        try
        {            
            Socket sock = new Socket("127.0.0.1", 12345);         
            DataInputStream dIn=new DataInputStream(sock.getInputStream());
            fileName=dIn.readUTF();
            jLabel3.setText(fileName);
            dIn.close();
            sock.close();
        }
        catch(Exception e)
        {
           JOptionPane.showMessageDialog(mainPanel, "file name: "+e);
        }
               JOptionPane.showMessageDialog(mainPanel, "file is being recieved . . . ");
        try
        { 
            Socket sock = new Socket("127.0.0.1", 12345);
            byte[] mybytearray = new byte[1024000];
            System.out.println("1");
            InputStream is = sock.getInputStream();
            System.out.println("2");
            File recievedFile=new File("Z:\\"+fileName);
            System.out.println("3");
            recievedFile.createNewFile();
            System.out.println("4");           
            FileOutputStream fos = new FileOutputStream(recievedFile);
            System.out.println("5");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            System.out.println("6");
            int bytesRead = is.read(mybytearray, 0, mybytearray.length);
            System.out.println("7");
            bos.write(mybytearray, 0, bytesRead);
            System.out.println("8");
            bos.flush();
            System.out.println("9");
            bos.close();
            sock.close();  
        }
        catch(Exception e)
        {
           JOptionPane.showMessageDialog(mainPanel, "file sending: "+e);
        }
    }                                     

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration                   
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
 }
LisaMM
  • 675
  • 1
  • 16
  • 28
Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46

4 Answers4

3

Maybe your file is bigger than 1024 bytes? It's bigger than the buffer

Edit: The error is because of this line:

FileOutputStream fout=new FileOutputStream(path); 

Comment it out because you don't really do anything with it. It's in the serverside code one of the first lines in your first try-catch

This line opens an output-Stream to your file. Nothing happens with this stream but it's also not closed.

This causes not only the error on the client side (because no data is transfered), but also wipes out all data you store in your file.

Edit 2:

I tried a picture with the bytesize of 305564

and although the buffer on the client side was big enough i just got 65536 bytes of data transferred at the same time.

For big files you have to use loops to get all needed data filled in to your buffer:

I tested it out because i wanted to get it work, too.

Client Side

try
                { 
                    Socket sock = new Socket("127.0.0.1", 12345);
                    byte[] mybytearray = new byte[65536];
                    System.out.println("1");
                    InputStream is = sock.getInputStream();
                    System.out.println("2");
                    File recievedFile=new File(fileName+"_res.jpg");
                    System.out.println("3");
                    recievedFile.createNewFile();
                    System.out.println("4");           
                    FileOutputStream fos = new FileOutputStream(recievedFile);
                    System.out.println("5");
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    System.out.println("6");
                    int loopcount = is.read();

                    for(int i = 0; i < loopcount; i++)
                    {
                        int bytesRead = is.read(mybytearray, 0, mybytearray.length);
                        System.out.println(bytesRead);
                        System.out.println("7");
                        bos.write(mybytearray, 0, bytesRead);
                        System.out.println("8");
                        bos.flush();
                    }

                    System.out.println("9");
                    bos.close();
                    sock.close();  
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

Server Side

 try
            {               
                 ServerSocket servsock=new ServerSocket(12345);
                 Socket sock = servsock.accept();
                     int bufferSize = 65536;
                     byte[] mybytearray = new byte[bufferSize];
                     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                     OutputStream os = sock.getOutputStream();
                     int loopcount = (int) (file.length()/bufferSize)+(file.length()%bufferSize==0?0:1);
                     System.out.println("loopcount: "+loopcount);
                     os.write(loopcount);
                     os.flush();
                     for(int i = 0; i < loopcount; i ++)
                     {
                         System.out.println(i);
                     bis.read(mybytearray, 0, mybytearray.length);

                     //System.out.println(mybytearray.length);
                     os.write(mybytearray, 0, mybytearray.length);
                     os.flush();
                     }

                     os.close();
                     sock.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
Loki
  • 4,065
  • 4
  • 29
  • 51
  • I had allready tried this but still in vain. Could you care to exaplain this part becasue i am unable to decode it. – Nitesh Verma Jul 31 '13 at 12:28
  • Can you post the whole classes for Client and Server? Or at least the upper functions within the function-body? So i can test it out. – Loki Jul 31 '13 at 12:31
  • Yes but i also wrote the solution to your error. Look after the Edit in my post – Loki Jul 31 '13 at 13:05
  • This line of code cannot cause an ArrayIndexOutOfBoundsException. -1 – user207421 Jul 31 '13 at 13:09
  • Good catch +1, especially since that's undocumented behaviour. – kiheru Jul 31 '13 at 13:10
  • It cannot cause the exception on the server side. But on the client side because no data is coming and that is caused by this line so thats the reason of the ArrayIndexOutOfBoundsException – Loki Jul 31 '13 at 13:10
  • Thank you very much. You are a real genious. I could have never seen its damage if i were working on it for weeks. I see this can serve as a good hack! – Nitesh Verma Jul 31 '13 at 13:12
  • Could you please check on that if you are able to send .jpeg, .png and .mp3 files because here i am getting exception error and corrupted pictures. It would be very helpful. – Nitesh Verma Jul 31 '13 at 13:17
  • Exception on server side while sending image files: Connection reset by peer: socket write error(java.SocketException) – Nitesh Verma Jul 31 '13 at 13:19
  • Well for this type of datatypes i think your buffer is too small – Loki Jul 31 '13 at 13:19
  • @NiteshVerma use a suitable sized buffer and write the content in a loop for transferring large fires. Similarly reading should be done in a loop. – kiheru Jul 31 '13 at 13:22
  • I just tried to get it to work, if it works for you feel free to use the code. – Loki Jul 31 '13 at 13:44
  • But test it out. I don't know if something is missing. Maybe you can get strange results. – Loki Jul 31 '13 at 13:54
  • YEs its working fine on my system, but when i am running it on a network i get an error, connection refused. I have used the IP=Inet4Address.getLocalHost().getHostAddress(); to get the ip of the system. What could have went wrong now? – Nitesh Verma Aug 01 '13 at 06:46
  • getHostAdress() is giving you the IP-Adress in your Local Network. You have to get your Internet IP Adress, which is different. http://www.whatismyip.com/ To get the IP Adress in Java you could use the solution shown here: http://stackoverflow.com/questions/2939218/getting-the-external-ip-address-in-java – Loki Aug 01 '13 at 06:49
  • The solution of the link i gave you doesn't work. But the Answer with 9 Upvotes should work. Use this. – Loki Aug 01 '13 at 06:52
2

InputStream.read() returns -1 at the end of the stream. You are passing that to bos.write().

int bytesRead = is.read(mybytearray, 0, mybytearray.length);
System.out.println("7");
bos.write(mybytearray, 0, bytesRead);

From the documentation:

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

kiheru
  • 6,588
  • 25
  • 31
  • Allright, i got it now. That means i am not aple to put the file in the output stream on the server side? – Nitesh Verma Jul 31 '13 at 13:00
  • @NiteshVerma probably. I haven't taken a good look at the server side. Just at the client side error (which you should handle whether the server is fixed or not). – kiheru Jul 31 '13 at 13:04
  • YEs its working fine on my system, but when i am running it on a network i get an error, connection refused. I have used the IP=Inet4Address.getLocalHost().getHostAddress(); to get the ip of the system. What could have went wrong now? – Nitesh Verma Aug 01 '13 at 06:47
  • @NiteshVerma Loki already answered, but that should have really been a new question, as it was a new problem. There'd be more people ready to help too. – kiheru Aug 01 '13 at 06:59
1

Server Module

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerMain {

  public static void main(String[] args) throws IOException {

    ServerSocket servsock = new ServerSocket(6789);

    File myFile = new File("ServerMain.java");

    while (true) {

      Socket sock = servsock.accept();

      byte[] mybytearray = new byte[1024];

      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));

      OutputStream os = sock.getOutputStream();
       int count;
            while ((count = bis.read(mybytearray)) >= 0) {
                 os.write(mybytearray, 0, count);

            }

      os.flush();
      sock.close();
    }
  }
}

Client Module:

public class ClientMain {

  public static void main(String[] argv) throws Exception {

    Socket sock = new Socket("127.0.0.1", 6789);

    byte[] mybytearray = new byte[1024];

    InputStream is = sock.getInputStream();

    FileOutputStream fos = new FileOutputStream("Demo1.java");

    BufferedOutputStream bos = new BufferedOutputStream(fos);

     int count;

            while ((count = is.read(mybytearray)) >= 0) {

             System.out.println(count);

                         bos.write(mybytearray, 0, count);
            }

    bos.close();
    sock.close();
  }
}

Here this works for me and I noticed from your code that you have taken

byte[] mybytearray = new byte[(int) file.length()];

it should be

byte[] mybytearray = new byte[1024];

hope this will work for you.

LisaMM
  • 675
  • 1
  • 16
  • 28
  • are you able to send .jped or .png files without getting it corrupted? – Nitesh Verma Jul 31 '13 at 13:29
  • Yes. i tried it with .jpg file and it gives output as expected. – Ilesh Patel Jul 31 '13 at 13:47
  • YEs its working fine on my system, but when i am running it on a network i get an error, connection refused. I have used the IP=Inet4Address.getLocalHost().getHostAddress(); to get the ip of the system. What could have went wrong now? – Nitesh Verma Aug 01 '13 at 06:47
1

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

Your file is reached End of stream so its return -1. So you are getting ArrayIndexOutOfException

Replace with this code

 Socket sock = new Socket("127.0.0.1", 12345);
 byte[] mybytearray = new byte[1024];
 System.out.println("1");
 InputStream is = sock.getInputStream();
 System.out.println("2");
 File recievedFile=new File("Z:\\"+fileName);
 System.out.println("3");
 recievedFile.createNewFile();
 System.out.println("4");           
 FileOutputStream fos = new FileOutputStream(recievedFile);
 System.out.println("5");
 BufferedOutputStream bos = new BufferedOutputStream(fos);
 System.out.println("6");
 int bytesRead  = 0;
 while((bytesRead = is.read(mybytearray, 0, mybytearray.length))>0)
 {    
      System.out.println("mybytearray : " +mybytearray.length +" bytesRead :"+bytesRead);
      bos.write(mybytearray, 0, bytesRead);
      System.out.println("8");
 }

  bos.flush();
 System.out.println("9");
 bos.close();
 sock.close();  
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • YEs its working fine on my system, but when i am running it on a network i get an error, connection refused. I have used the IP=Inet4Address.getLocalHost().getHostAddress(); to get the ip of the system. What could have went wrong now? – Nitesh Verma Aug 01 '13 at 06:46
  • 1
    Replace with your server ip and server listening port. Socket sock = new Socket("Server IP", Server Port); Ensure your network connection by ping the server ip (type ping serverip in windows command line) from your client machine. – Prabhakaran Ramaswamy Aug 01 '13 at 06:58