当我使用套接字编程传输大型文件时,接收到的文件是不完整的,即播放时声音不正常。以下是代码:
服务器端代码:
在客户端,我仅为简单起见使用了
服务器端代码:
File myFile = new File("abc.mp3");
{
Socket sock = servsock.accept();
int packetsize=1024;
double nosofpackets=Math.ceil(((int) myFile.length())/packetsize);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
for(double i=0;i<nosofpackets+1;i++) {
byte[] mybytearray = new byte[packetsize];
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("Packet:"+(i+1));
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0,mybytearray.length);
os.flush();
}
}
客户端:
int packetsize=1024;
FileOutputStream fos = new FileOutputStream("zz.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
double nosofpackets=Math.ceil(((int) (new File("abc.mp3")).length())/packetsize);
for(double i=0;i<nosofpackets+1;i++)
{
InputStream is = sock.getInputStream();
byte[] mybytearray = new byte[packetsize];
int bytesRead = is.read(mybytearray, 0,mybytearray.length );
System.out.println("Packet:"+(i+1));
bos.write(mybytearray, 0,mybytearray.length);
}
sock.close();
bos.close();
在客户端,我仅为简单起见使用了
new File("abc.mp3")).length
(我可以从服务器端发送文件长度)。如果客户端和服务器在同一台机器上,则此代码完美运行,但如果它们在不同的机器上,则文件会变形。