简体   繁体   中英

java file transfer socket write error

I'm working on a client-server file transfer project, I've almost completed my tests on localhost but today got an error below, here are the source codes of client and server:

Client side

   public class Client {

    public static void main(String args[]) {
        String receiverIP = null;
        int serverPort = 0;
        receiverIP = args[0];
        serverPort = Integer.parseInt(args[1]);
        String fileToSend = args[2]; 
        byte[] aByte = new byte[1];
        int bytesR;
        Socket clientSocket = null;
        BufferedOutputStream bos = null;
        InputStream is = null;

        try {
            clientSocket = new Socket(receiverIP, serverPort);
            bos = new BufferedOutputStream(clientSocket.getOutputStream());           
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            ex.printStackTrace();
        }    

        if (is != null) {           
            FileOutputStream fos = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {

                    File myFile = new File( fileToSend );
                    System.out.println("The file chosen is being sent...");
                    byte[] mybytearray = new byte[(int) myFile.length()];
                    FileInputStream fis = null;

                    try {
                        fis = new FileInputStream( myFile );
                    } catch (FileNotFoundException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        bis.read(mybytearray, 0, mybytearray.length);
                        bos.write(mybytearray, 0, mybytearray.length);
                        bis.close();

                        return;
                    }catch (IOException ex) {
                        ex.printStackTrace();
                    }

                File file = new File("C:\\copy.jpg");
                fos = new FileOutputStream( file );
                bos = new BufferedOutputStream(fos);
                bytesR = is.read(aByte, 0, aByte.length);
                do {
                        baos.write(aByte);
                        bytesR = is.read(aByte);
                } while (bytesR != -1);
                System.out.println("File transfer successful");

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Server side

    public class Server {

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            BufferedOutputStream ToClient = null;

            try {
                welcomeSocket = new ServerSocket(3249);
                System.out.println("The port " + welcomeSocket.getLocalPort() + " is opened and ready for use.");
                Socket connectionSocket = welcomeSocket.accept();

                ToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

here is the error I get

    The file chosen is being sent...
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.BufferedOutputStream.write(Unknown Source)
    at Client.main(Client.java:44)
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at Client.main(Client.java:55)

I'm nearly sure this error is not about closing the server socket before all data is transmitted, and about the reading and writing process on the bytearray but all my fix attempts were in vain, maybe I've misplaced the streams so they do not work as intended, (the copy.jpg file is created but not getting any streams) any help would be appreciated

edit: I forgot to mention, currently I'm using a wireless internet connection and I've read a little about socket porgramming that mentions wireless networks are unreliable to test on

Your server side does not wait for data to be received. It accepts the connection and then continues with the next loop cycle immediately. This causes your initial server socket and socket to client to be garbage-collected and thus closed.

You can verify this behaviour by using telnet, which is very handy when it comes to checking servers in general. Open a command prompt on the server machine (cmd or a console) and run this command to connect to your server:

telnet localhost 3249

You will see that it connects and then gets disconnected almost immediately, just like your own client application.

The solution is that additionally to the code for accepting the connection on the server side, you need to write code there for receiving the data.

Moreover, you should put the creation of the server socket in front of the loop instead of inside the loop. You need to create the server socket only once and you can then accept arbitrarily many connections through it. Opening the server socket more than once will fail, because the port is still occupied (freeing the port often takes a few seconds in some operating systems, even when the previous server socket has been closed).

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