简体   繁体   English

Java文件传输套接字写入错误

[英]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: 我正在做一个客户端-服务器文件传输项目,我几乎在localhost上完成了测试,但是今天下面出现错误,这是客户端和服务器的源代码:

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 我几乎可以肯定,该错误不是与所有数据都被传输之前关闭服务器套接字有关,以及与字节数组上的读写过程有关,但是我所有的修复尝试都是徒劳的,也许我放错了流,所以它们没有按预期工作(创建copy.jpg文件但未获得任何流)任何帮助将不胜感激

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. 您可以通过使用telnet来验证此行为,这在通常检查服务器时非常方便。 Open a command prompt on the server machine (cmd or a console) and run this command to connect to your server: 在服务器计算机(cmd或控制台)上打开命令提示符,然后运行以下命令以连接到服务器:

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). 多次打开服务器套接字将失败,因为该端口仍被占用(在某些操作系统中,即使关闭了先前的服务器套接字,释放端口通常也要花费几秒钟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM