1

こんにちは、(.txt、.JPEG、.docx、.mp3、.wma) など、あらゆる種類のファイルを転送できる小さなクライアント ファイル サーバー アプリケーションを実行しようとしています。これまでのところ、転送はランダムにのみ行うことができました。ほとんどの場合、ファイルは転送されません。イメージのみがクライアント パスに出力されます。

ファイルが do while ループで動かなくなっているようです。これを解決するのを手伝ってください。

サーバー部分:

    // create socket
    ServerSocket serversock = new ServerSocket(444);

    while (true) {

        System.out.println("Waiting for client to connect...");
        Socket welcomesock = serversock.accept();
        System.out.println("Client has connected from: " + welcomesock.getInetAddress().getHostAddress());


        File myFile = new File ("C:\\temp\\New Stories.wma");

        if(!myFile.exists()){
            System.out.println("Filename does not exist");
            welcomesock.close();
        }

        else{
            byte [] mybytearray  = new byte [(int)myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);

            BufferedInputStream bis = new BufferedInputStream(fis);

            bis.read(mybytearray,0,mybytearray.length);     

            OutputStream os = welcomesock.getOutputStream();

            System.out.println("Sending file");

            os.write(mybytearray,0,mybytearray.length);

            os.flush();

            os.close();

            }
        }</i>

クライアント部分:

while(真){

        int bytesRead;
        int currentlength = 0;
        int fsize=6022386; // filesize temporary hardcoded
        long start = System.currentTimeMillis();


        // Creates the Client socket and binds to the server
        Socket clientSocket = null;

        try {
            clientSocket = new Socket(127.0.0.1, 444);
            } catch (UnknownHostException e) {
                e.printStackTrace();
                }




        byte [] bytearray  = new byte [fsize];
        InputStream is = clientSocket.getInputStream();


        FileOutputStream fos = new FileOutputStream("D:\\New Stories.wma");

        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(bytearray,0,bytearray.length);
        currentlength = bytesRead;

        do {
            bytesRead = is.read(bytearray, currentlength, (bytearray.length-currentlength));
            if(bytesRead >= 0) currentlength += bytesRead;

        } while(bytesRead > -1);

        bos.write(bytearray, 0 , currentlength);
        bos.flush();
        long end = System.currentTimeMillis();
        System.out.println(end-start);

        bos.close();
        clientSocket.close();



    }

4

1 に答える 1

0

サーバー部分に無限ループがあります。

while (true){
   ...
}

決して抜けません。次のように変更することをお勧めします。

if(!myFile.exists()){
        System.out.println("Filename does not exist");
        welcomesock.close();
    }

if(!myFile.exists()){
        System.out.println("Filename does not exist");
        welcomesock.close();
        break;
    }

ファイルが存在しない場合、ループを終了します。

于 2013-11-04T10:05:47.560 に答える