无法让我的 Java 服务器接受来自我的客户端的文件传输 [英] Can't get my java server to accept a file transfer from my client
问题描述
我有两个文件:一个聊天服务器和一个聊天客户端.聊天客户端应该说它想将文件上传到服务器.然后它上传.但是,现在,所有消息都被正确发送/接收,但是当我尝试进行文件传输时,我唯一得到的是一个 0 字节的文件(位于我在服务器类中指定的路径中).
I have two files: a chat server and a chat client. The chat client is supposed to say that it wants to upload a file to the server. And then it uploads. However, right now, all of the messages are being sent / received properly, but when I try to get the file transfer, the only thing I get is a file with 0 bytes (which is at the path I specify inside of the server class.
chatclient 类的损坏部分:
Broken part of the chatclient class:
/**
* Sends a broadcast to the server
*/
public static void broadcast() throws IOException {
if (UserInput.getText() == "/upload") {
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = Socket.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
System.out.println("" + UserInput.getText());
outputStream.println(UserInput.getText());
outputStream.flush();
}
服务器类的损坏部分:
if (input.contains("/upload")) {
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = csocket.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if (bytesRead >= 0) current += bytesRead;
}
while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
}
推荐答案
你的复制循环是无稽之谈.在 Java 中复制流的规范方法如下:
Your copy loop is nonsense. The canonical way to copy a stream in Java is as follows:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
其中 'count' 是一个整数,'buffer' 是一个长度 > 0 的 byte[] 数组.我通常使用 8192.
where 'count' is an int, and 'buffer' is a byte[] array of length > 0. I usually use 8192.
这篇关于无法让我的 Java 服务器接受来自我的客户端的文件传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!