我的文件从服务器传输到客户端有问题。问题是,即使文件有多大,最后的字节也不会被传输。假设我想下载56kb的文件,然后我只收到35kb的例子。
我将为您提供一些代码片段,也许有人可以看到任何错误。
发件人:
public void sendFile(String fileName, Socket socket) {
try {
try {
File transferFile = new File(fileName);
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream os = socket.getOutputStream();
int bytesRead = 0;
while (-1 != (bytesRead = bin.read(bytearray, 0, bytearray.length))) {
os.write(bytearray, 0, bytesRead);
}
bin.close();
os.flush();
socket.close();
} catch (IOException e) {
System.out.println("error " + e);
}
} catch (Exception ex) {
System.out.println("error " + ex);
}
}
接收者:
public void downloadFile(Socket socket, String fName) {
try {
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int count;
byte[] buffer = new byte[1024];
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
bos.close();
} catch (Exception e) {
System.out.println("Error " + e);
}
}
欢迎任何帮助,谢谢。
答案 0 :(得分:0)
char* fn = NULL;
SDL_Log("fn pre address is: %p\n",fn);
fn = get_resource("test.txt");
SDL_Log("fn pos address is: %p\n",fn);
//free(fn); <--this causes seg fault if I uncomment it
INFO: fn pre address is: 0x0
INFO: fn pre address is: 0x7fa882501a00
INFO: fn pos address is: 0x7fa882501a00
get_resource(const char* filename) {
char* string = (char*)calloc(1, sizeof(strlen(res_dir) + strlen(filename)));
//i also tried with strncpy
//strncpy(string, res_dir, strlen(res_dir));
//strncpy(string + strlen(res_dir), filename, strlen(filename));
memcpy(string, "/usr/test/files", strlen(res_dir));
memcpy(string + strlen("/usr/test/files"), filename, strlen(filename));
string[strlen(filename) + strlen("/usr/test/files")] = '\0';
return string;
}
返回零, while ((count = is.read(buffer)) > 0)
将中断循环。
但是,如果返回零,则不应假设已到达文件末尾,因为根据文档,零是一个完全有效的返回值。
你应该继续阅读,直到is.read()
被退回。
此外,关闭-1
后,您还应该关闭BufferedOutputStream bos
。