gpt4 book ai didi

java - 文件传输陷入 do while 循环

转载 作者:行者123 更新时间:2023-12-01 04:12:44 25 4
gpt4 key购买 nike

您好,我正在尝试制作一个小型客户端文件服务器应用程序,其中可以传输任何类型的文件,包括(.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(true){

        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();



}

最佳答案

您的服务器部分有一个无限循环:

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;
}

当不存在文件时,它将退出循环。

关于java - 文件传输陷入 do while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19765349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com