Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用套接字上载文件_Java_Sockets - Fatal编程技术网

Java 使用套接字上载文件

Java 使用套接字上载文件,java,sockets,Java,Sockets,我能够上传任何类型的文件到服务器使用下面的代码。然而,在上传完成后,我在服务器上收到一条错误消息,上面说 java.net.SocketException:套接字已关闭 线程thread-0 java.lang.NullPointerException中出现异常 在Server2Connection.runserver1.java:407 位于java.lang.Thread.runUnknown Source server1.java:407在服务器代码中引用了行开关clientMsg。文件没

我能够上传任何类型的文件到服务器使用下面的代码。然而,在上传完成后,我在服务器上收到一条错误消息,上面说

java.net.SocketException:套接字已关闭 线程thread-0 java.lang.NullPointerException中出现异常 在Server2Connection.runserver1.java:407 位于java.lang.Thread.runUnknown Source

server1.java:407在服务器代码中引用了行开关clientMsg。文件没有正确上传。但我似乎并没有正确地使用。关闭指示。在此之后,服务器不会断开连接,但客户机再次循环,只是为了断开连接。谁能告诉我我把事情搞砸了吗?谢谢

服务器端:

public BufferedReader msgFromClient() throws IOException {
    BufferedReader receiveClientmsg = null;

    try {
        receiveClientmsg = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    } catch (IOException e) {
        System.out.println(e);
    }
    return receiveClientmsg;
}

public DataOutputStream outToClient() throws IOException {
    DataOutputStream sendClientmsg = null;

    try {
        sendClientmsg = new DataOutputStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    return sendClientmsg;
}

public void upload() throws IOException {
    byte[] mybytearray = new byte[8192];
    InputStream is = clientSocket.getInputStream();
    String file_name = msgFromClient().readLine();
    File rqstd_upld_file = new File(SERVER_FILE_LOCATION + file_name);

    if (rqstd_upld_file.exists()){
        outToClient().writeBytes("yes\n");
        outToClient().writeBytes("A file with the name " + file_name + " already exists on server\n");
        System.out.println("A file with the name " + file_name + " already exists");
    }
    else {
        outToClient().writeBytes("no\n");
        FileOutputStream fos = new FileOutputStream(SERVER_FILE_LOCATION +"\\"+ file_name);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int count;
        System.out.println("Downloading " + file_name + " ...");
        outToClient().writeBytes("Uploading. Please wait...\n");
        while ((count = is.read(mybytearray)) > 0){
            bos.write(mybytearray, 0, count);
        }
        System.out.println("Download Successful");
        is.close();
        bos.close();
    }
}
try {
        while (true) {
            //Message sent by the client
            String clientMsg = server.msgFromClient().readLine();               

            switch (clientMsg) {
            case "1":
                //'Upload file' command from client
                System.out.print("\nCommand from " + clientSocket.getInetAddress() + ":"+ clientSocket.getPort()+" : ");
                System.out.println("Upload file");
                server.upload();
                break;

            case "1fail":
                //In case client fails to find the file it wants to upload
                System.out.print("\nCommand from " + clientSocket.getInetAddress() + ":"+ clientSocket.getPort()+" : ");
                System.out.println("Upload file");
                System.out.println("Client could not upload: File did not exist on client machine\n");
                break;
}
catch(IOException e){
        System.out.println(e);
    }
客户端:

while (true) {
try{
Scanner scan0 = new Scanner(System.in);
String command = scan0.nextLine();

switch (command) {
case "1":
    //Upload file
    File file_to_upload = null;
    System.out.print("Enter file path: ");
    Scanner scan = new Scanner(System.in);
    String pathname = scan.nextLine();
    System.out.print("Enter file name: ");
    Scanner scan1 = new Scanner(System.in);
    String file = scan1.nextLine();
    Path path = Paths.get(pathname, file);
    file_to_upload = new File(path.toString());

    if (file_to_upload.exists()){   
        outToServer.writeBytes(command + '\n');
        outToServer.writeBytes(file + '\n');
        String existsOnServer = msgFromServer.readLine();

        switch (existsOnServer) {
        case "yes":
            System.out.println('\n'+ msgFromServer.readLine() + '\n');
            break;
        case "no":
            int count;
            System.out.println('\n'+ msgFromServer.readLine() + '\n');
            byte[] bytearray = new byte[8192];
            InputStream in = new FileInputStream(file_to_upload);
            BufferedInputStream bis = new BufferedInputStream(in);
            OutputStream os = client1.getOutputStream();
                while ((count = bis.read(bytearray)) > 0){
                os.write(bytearray, 0, count);
            }
            System.out.println("Done Uploading");
            os.close();
            in.close();
            bis.close();
            break;
        }
    }
    else{
        System.out.println("File " + path + " does not exist\n");
        outToServer.writeBytes("1fail" + '\n');
    }
    break;

    case "2":
//...
}
                catch(IOException e){
                    System.out.println(e);
                    break;
                }
}

您可能太早关闭了客户端strem,服务器无法完成对它的读取。尝试在关闭客户端的Stream和socket之前放置计时器。如果它能工作,您应该考虑一种更好的同步方式,允许服务器读取整个文件。

只需添加一个新命令即可关闭与服务器的连接

switch (clientMsg) {
        case "1":
            //'Upload file' command from client
            System.out.print("\nCommand from " + clientSocket.getInetAddress() + ":"+ clientSocket.getPort()+" : ");
            System.out.println("Upload file");
            server.upload();
            break;

        case "1fail":
            //In case client fails to find the file it wants to upload
            System.out.print("\nCommand from " + clientSocket.getInetAddress() + ":"+ clientSocket.getPort()+" : ");
            System.out.println("Upload file");
            System.out.println("Client could not upload: File did not exist on client machine\n");
            break;
        case "-1":
            is.close();

            break;

您正在为每个事务创建新的流并关闭它们。这会关闭套接字并导致下次出现异常


但这项技术无论如何都是无效的。您应该在套接字的生命周期中使用相同的流。您还需要安排对等方知道您要发送的文件中有多少数据,通常是提前发送,让对等方准确读取那么多字节,而不是像您现在这样读取到流的末尾。

服务器读取整个文件…只有在这之后才会发生错误。我尝试了一系列的文件类型和大小,从1KB的文本文件到3.5GB的视频文件。上传的文件完整且功能正常,这意味着它们不会损坏。错误仍然发生。您不需要计时器或延迟关闭。TCP中没有丢失数据。只是更改了clientSocket.getInputStream。我已编辑了服务器代码,以便在套接字存在期间使用相同的流。同样的错误仍然发生。