Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.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_Client Server - Fatal编程技术网

Java 通过套接字的客户机-服务器通信

Java 通过套接字的客户机-服务器通信,java,client-server,Java,Client Server,我试图通过套接字通信将数据从服务器发送到客户端,但在接收端收到一个错误 下面是我的代码片段- 服务器-此类称为CLIENTConnection,负责从服务器到客户端的所有连接 import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; import java.io.*; public class CLIENTConnection implements

我试图通过套接字通信将数据从服务器发送到客户端,但在接收端收到一个错误

下面是我的代码片段-

服务器-此类称为CLIENTConnection,负责从服务器到客户端的所有连接

    import java.net.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.io.*;
    public class CLIENTConnection implements Runnable {

private Socket clientSocket;
private BufferedReader in = null;

public CLIENTConnection(Socket client) {
    this.clientSocket = client;
}

@Override
public void run() {
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String clientSelection=in.readLine();
        while (clientSelection != null) {
            switch (clientSelection) {
                case "1":
                    receiveFile();
                    break;
                case "2":

                    System.out.println("inside case 2");
                    String outGoingFileName = in.readLine();
                    System.out.println(outGoingFileName);

                      while (outGoingFileName != null) {
                          System.out.println("Inside while loop");
                        sendFile(outGoingFileName);
                   }
                   System.out.println("Out of while");

                    break;

                case "3":
                    receiveFile();
                    break;

                default:
                    System.out.println("Incorrect command received.");
                    break;
            }
            in.close();
            break;
        }

    } catch (IOException ex) {
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void receiveFile() {
    try {

        int bytesRead;
        DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());

        String filename = clientData.readUTF();
        System.out.println(filename+" is received on server side");
        OutputStream output = new FileOutputStream(("C://Users/Personal/workspace/ClientServer/src/dir/"+filename));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        output.close();
        clientData.close();

        System.out.println("File "+filename+" received from client.");
    } catch (IOException ex) {
        System.err.println("Client error. Connection closed.");
    }
}



 public void sendFile(String fileName) {
try {
    //handle file read
    File myFile = new File("C://Users/Personal/workspace/ClientServer/src/dir/"+fileName);
    byte[] mybytearray = new byte[(int) myFile.length()];

    FileInputStream fis = new FileInputStream(myFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    //bis.read(mybytearray, 0, mybytearray.length);

    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(mybytearray, 0, mybytearray.length);

    //handle file send over socket
    OutputStream os = clientSocket.getOutputStream();

    //Sending file name and file size to the server
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(myFile.getName());
    dos.writeLong(mybytearray.length);
    dos.write(mybytearray, 0, mybytearray.length);
    dos.flush();
    System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
    System.err.println("File does not exist!");
} 
}
 }
客户端接收文件

  public class FileClient {



    private static Socket sock;
    private static String fileName;
    private static BufferedReader stdin;
    private static PrintStream os;

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream inFromServer; 



        try 
        {
            sock = new Socket("localhost", 7777);
            stdin = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            System.err.println("Cannot connect to the server, try again later.");
            System.exit(1);
        }


        inFromServer= new ObjectInputStream(sock.getInputStream());
        os = new PrintStream(sock.getOutputStream());


        try {
              switch (Integer.parseInt(selectAction())) {
            case 1:
                os.println("1");
                sendFile();
                break;
            case 2:
                os.println("2");
                System.err.print("Enter file name: ");
                fileName = stdin.readLine();
                os.println(fileName);
               receiveFile(fileName);
                break;

            case 3:
                os.println("3");
                Synchronise();

        }
        } catch (Exception e) {
            System.err.println("not valid input");
        }


        sock.close();


    }


    private static void Synchronise() 
    {
        HashMap<String, Calendar> ClientFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/Client/");//getting the filename and timestamp of all the files present in client folder. 
        /*System.out.println("Client File List : \n");
        for(String s : ClientFileList.keySet()) 
            System.out.println(s);*/
        HashMap<String, Calendar> ServerFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/src/dir/");//(HashMap<String, Calendar>) inFromServer.readObject();
        /*System.out.println("\nServer File List : \n");
        for(String s : ClientFileList.keySet()) 
            System.out.println(s);*/
        System.out.println("File comparision output");
        compareTimestamp(ClientFileList,ServerFileList);
    }




    private static void compareTimestamp(HashMap<String, Calendar> ClientFileList, HashMap<String, Calendar> serverFileList) 
    {
        LinkedList<String> fileToUpload=new LinkedList<String>();
        LinkedList<String> fileToDownload=new LinkedList<String>();
        LinkedList<String> fileToDeleteFromClient=new LinkedList<String>();
        LinkedList<String> fileToDeleteFromServer=new LinkedList<String>();
        Calendar clientCalender = null,serverCalendar=null;

        for (String filename : serverFileList.keySet()) 
        {
            serverCalendar=serverFileList.get(filename);
            if(ClientFileList.containsKey(filename))
            {
                clientCalender=ClientFileList.get(filename);
                if(clientCalender.before(serverCalendar))
                {
                    fileToDownload.add(filename);
                }
                else
                {
                    fileToUpload.add(filename);
                }
            }
            else
            {
                fileToDeleteFromClient.add(filename);
            }
        }

        for (String filename : ClientFileList.keySet()) 
        {
            clientCalender=ClientFileList.get(filename);
            if(!serverFileList.containsKey(filename))
            {
                fileToDeleteFromServer.add(filename);
            }
        }


        System.out.println("Files to download to client: "+fileToDownload);
        System.out.println("Files to upload to Server: "+fileToUpload);
        System.out.println("Files to delete from client: "+fileToDeleteFromClient);
        System.out.println("Files to delete from Server: "+fileToDeleteFromServer);

        sendFile(fileToDeleteFromServer);

    }


      private static HashMap<String, Calendar> getTimeStamp(String location) 
    {
        HashMap<String,Calendar> fileList = new HashMap<String,Calendar>();
        File dir = new File(location);

        File[] files = dir.listFiles();
        if (files.length == 0) 
        {
            System.out.println("No file found");
            //System.exit(1);
        }
        else
        {
            for (int i = 0; i < files.length; i++) 
            {
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(files[i].lastModified());
                fileList.put(files[i].getName(), calendar);
            }
        }
        return fileList;
    }



    public static String selectAction() throws IOException 
    {
        System.out.println("1. Send file.");
        System.out.println("2. Recieve file.");
        System.out.println("3. Synchronize");
        System.out.print("\nMake selection: ");

        return stdin.readLine();
    }

    public static void sendFile() 
    {
        try {
            System.err.print("Enter file name: ");
            fileName = stdin.readLine();

            File myFile = new File("C:/Users/Personal/workspace/ClientServer/Client/"+fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            //bis.read(mybytearray, 0, mybytearray.length);

            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);

            OutputStream os = sock.getOutputStream();

            //Sending file name and file size to the server
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName());
            dos.writeLong(mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);
            dos.flush();
            dis.close();
            System.out.println("File "+fileName+" sent to Server.");
        }
        catch (Exception e)
        {
            System.err.println("File does not exist!");
        }
    } 

    //receive a list of file to upload to server from client.
    static void sendFile(LinkedList<String> fileList)
    {
        for(String file: fileList)
            sendFile(file);
    }

    public static void sendFile(String filename) {
            File file = new File("C:/Users/Personal/workspace/ClientServer/Client/"+filename);
            byte[] mybytearray = new byte[(int) file.length()];
            FileInputStream fis;
            try 
            {
                fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                //bis.read(mybytearray, 0, mybytearray.length);

                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);

                OutputStream os = sock.getOutputStream();

                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(file.getName());
                dos.writeLong(mybytearray.length);
                dos.write(mybytearray, 0, mybytearray.length);
                dos.flush();
                dis.close();
                System.out.println("File "+filename+" sent to Server.");

            } 
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    public static void receiveFile(String fileName) {
        try {
            int bytesRead;
            InputStream in = sock.getInputStream();
            DataInputStream clientData = new DataInputStream(in);
             fileName = clientData.readUTF();
            OutputStream output = new FileOutputStream(("received_from_server_"));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }

            output.close();
            in.close();

            System.out.println("File "+fileName+" received from Server.");
        } catch (IOException ex) {
            Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
请告诉我是否有任何可能的解决方案。

DataInputStreams使用此异常来表示流结束。因此,中的异常可能不是错误,只是表示数据已发送

在阅读之前,你必须检查你是否确实收到了一些东西,然后再阅读

检查:
此异常主要由数据输入流用于向流结束发送信号。请注意,许多其他输入操作在流结束时返回一个特殊值,而不是引发异常。

您正在获取该文件吗

public static void receiveFile(String fileName) {
        boolean recieving = true;  //new
        while(recieving){ //new
        try {
        int bytesRead;
        InputStream in = sock.getInputStream();
        DataInputStream clientData = new DataInputStream(in);
         fileName = clientData.readUTF();
        OutputStream output = new FileOutputStream(("received_from_server_"));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        output.close();
        in.close();

        System.out.println("File "+fileName+" received from Server.");
    }  catch (EOFException e){   // new
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
        recieving = false;
    }  catch (IOException ex) {
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
    } //new
}

它显示了什么错误?请添加stacktrace。是否正在尝试为方法参数赋值?如果您以后不需要它,您应该使用本地var,或者如果调用方需要它,则返回它,而不是使方法无效,2014年6:00:43 AM FileClient接收文件严重:null java.io.DataInputStream.readFullyUnknown Source at java.io.DataInputStream.readUTFUnknown Source at java.io.DataInputStream.readUTFUnknown Source at FileClient.receiveFileFileClient.java:280 atjava:53能否将FileClient.main添加到问题中的代码片段中?在这种情况下,您应该提供一个可执行示例。。。补充。请查收,没错!文件已发送,但我无法捕获它。您能建议我们如何捕获它吗?正如这所建议的,您应该添加一个适当的终止条件现在,数据甚至没有被发送。不要使用可用的。它不会做你期望的事情!试过了,似乎不起作用。无法接收文件。
public static void receiveFile(String fileName) {
        boolean recieving = true;  //new
        while(recieving){ //new
        try {
        int bytesRead;
        InputStream in = sock.getInputStream();
        DataInputStream clientData = new DataInputStream(in);
         fileName = clientData.readUTF();
        OutputStream output = new FileOutputStream(("received_from_server_"));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        output.close();
        in.close();

        System.out.println("File "+fileName+" received from Server.");
    }  catch (EOFException e){   // new
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
        recieving = false;
    }  catch (IOException ex) {
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
    } //new
}