【问题标题】:ArrayIndexOutOfBounds exception in java socket programjava socket程序中的ArrayIndexOutOfBounds异常
【发布时间】:2013-07-31 23:15:45
【问题描述】:

我正在开发客户端/服务器程序上的 Swing 应用程序,用于通过 Java 套接字发送不同类型的文件。我已使用以下链接作为参考:File Transfer in Java

我已经按照我的要求修改了代码如下:

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

服务器端代码:

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

客户端代码:

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

我真的无法解决为什么在他接收文件时我在客户端的bos.write(mybytearray, 0, bytesRead); 行上收到ArrayOutOfBoundException

编辑:

代码结构有点复杂,但我敢打赌,你一定能找到函数。实际上客户端和服务器都使用不同的按钮在同一个窗口上实现。

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

【问题讨论】:

    标签: java swing sockets file-io indexoutofboundsexception


    【解决方案1】:

    也许您的文件大于 1024 字节?它比缓冲区大

    编辑: 错误是因为这一行:

    FileOutputStream fout=new FileOutputStream(path); 
    

    将其注释掉,因为您实际上并没有对它做任何事情。 它在服务器端代码中,是您第一次尝试捕获的第一行之一

    这一行打开一个输出流到你的文件。此流没有任何反应,但也没有关闭。

    这不仅会导致客户端出错(因为没有数据传输),还会清除您存储在文件中的所有数据。

    编辑 2:

    我试了一张字节大小为 305564 的图片

    虽然客户端的缓冲区足够大,但我同时传输了 65536 字节的数据。

    对于大文件,您必须使用循环将所有需要的数据填充到缓冲区中:

    我测试了它,因为我也想让它工作。

    客户端

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

    服务器端

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

    【讨论】:

    • 我已经尝试过了,但仍然徒劳无功。您能否解释一下这部分,因为我无法对其进行解码。
    • 您可以发布客户端和服务器的整个课程吗?或者至少是函数体内的上层函数?所以我可以测试一下。
    • 是的,但我也为您的错误写了解决方案。照顾我帖子中的编辑
    • 这行代码不会导致 ArrayIndexOutOfBoundsException。 -1
    • 不错的 +1,尤其是因为这是未记录的行为。
    【解决方案2】:

    InputStream.read() returns -1 在流的末尾。您将其传递给bos.write()

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

    来自documentation

    如果 off 为负数,或者 len 为负数,或者 off+len 大于数组 b 的长度,则抛出 IndexOutOfBoundsException。

    【讨论】:

    • 好的,我现在知道了。这意味着我不能将文件放在服务器端的输出流中?
    • @NiteshVerma 可能。我没有好好看看服务器端。就在客户端错误(无论服务器是否固定,您都应该处理)。
    • 是的,它在我的系统上工作正常,但是当我在网络上运行它时出现错误,连接被拒绝。我使用了 IP=Inet4Address.getLocalHost().getHostAddress();获取系统的ip。现在可能出了什么问题?
    • @NiteshVerma Loki 已经回答了,但这应该是一个新问题,因为它是一个新问题。也会有更多的人愿意提供帮助。
    【解决方案3】:

    如果 len 为零,则不读取任何字节并返回 0;否则,将尝试读取至少一个字节。如果由于流位于文件末尾而没有可用字节,则返回值 -1;否则,至少读取一个字节并将其存储到 b 中。

    您的文件已到达流的末尾,因此它返回 -1。所以你得到 ArrayIndexOutOfException

    用此代码替换

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

    【讨论】:

    • 是的,它在我的系统上工作正常,但是当我在网络上运行它时出现错误,连接被拒绝。我使用了 IP=Inet4Address.getLocalHost().getHostAddress();获取系统的ip。现在可能出了什么问题?
    • 替换为你的服务器ip和服务器监听端口。 Socket sock = new Socket("服务器 IP", 服务器端口);通过从客户端计算机 ping 服务器 ip(在 Windows 命令行中键入 ping serverip)确保您的网络连接。
    【解决方案4】:

    服务器模块

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

    客户端模块:

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

    这对我有用,我从你的代码中注意到你已经采取了

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

    应该是

    byte[] mybytearray = new byte[1024];

    希望这对你有用。

    【讨论】:

    • 您能否发送 .jped 或 .png 文件而不会损坏文件?
    • 是的。我用 .jpg 文件试了一下,它按预期给出了输出。
    • 非常感谢
    • 是的,它在我的系统上工作正常,但是当我在网络上运行它时出现错误,连接被拒绝。我使用了 IP=Inet4Address.getLocalHost().getHostAddress();获取系统的ip。现在可能出了什么问题?
    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    相关资源
    最近更新 更多