Java套接字,接收半空文件

时间:2019-03-11 02:02:02

标签: java sockets networking

晚上好,我正在Java上编写音乐服务,其中服务器计算机上有音乐文件,客户端计算机通过套接字连接到该套接字,然后继续下载选定的歌曲。

在使用同一台机器进行服务器-客户端操作时,文件传输已完成并且已完全播放。

但是当使用不同的机器时,文件将按其完整大小分配,但内容为空,实际上只播放歌曲的前两秒。

这是服务器的代码:

//dos = DataOutputStream();
//song = path received thru dos.writeUTF(string);

File file = new File(song);
dos.writeUTF(file.getName());
dos.flush();
FileInputStream fin = new FileInputStream(file); 
int size = (int) file.length();
byte b[] = new byte[size];
int read;
dos.writeUTF(Long.toString(size));
dos.flush();
System.out.println("Size: " + size);
System.out.println("Buf size: " + s.getReceiveBufferSize());
while ((read = fin.read(b)) != -1) {
    dos.write(b, 0, read);
    dos.flush();
}
fin.close();
while (dis.available() > 0);

这是给客户的:

//dis = DataInputStream();
dos.writeUTF(p.toString()); //Send the path of the file that wants to download
song = dis.readUTF();
System.out.println("Receving file: " + song);
System.out.println("Saving as file: " + song);
int sz = Integer.parseInt(dis.readUTF());
System.out.println("Receiving " + sz + " bytes of data");
System.out.println("File Size: " + (sz / (1024 * 1024)) + " MB");
byte b[] = new byte[sz];
System.out.println("Receving file..");
FileOutputStream fos = new FileOutputStream(new File(p.getFileName().toString()), true);
long bytesRead;
do {
    bytesRead = dis.read(b, 0, b.length);
    fos.write(b, 0, b.length);
} while (!(bytesRead < sz));
System.out.println("Comleted");
fos.close();

您需要完整的代码,这里是github: AntDraws13/MusicServer

我知道以这种方式发送文件效率低下且不安全,但这仅适用于学校项目,谢谢!

0 个答案:

没有答案