繁体   English   中英

通过套接字进行客户端-服务器通信

[英]Client-Server communication via Socket

我正在尝试通过套接字通信将数据从服务器发送到客户端,并且在接收端收到错误消息。

这是我的代码段-

服务器-此类称为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);
        }
    }

}

它向我显示错误

   filename = clientData.readUTF();

请让我知道是否有任何可能的解决方案。

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

阅读之前,您必须检查您是否确实收到了某些东西,然后再阅读。


检查This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.

您收到文件了吗?

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
}

暂无
暂无

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

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