【发布时间】:2020-09-10 04:12:07
【问题描述】:
我正在制作一个项目,其中一部分是关于使用 TCP 将 mp3 文件从客户端传输到服务器。我的想法是客户端将通过 FileInputStream 将 mp3 转换为字节数组,连接到套接字的输出流将字节数组传递给服务器。服务器会通过socket的Input Stream获取字节数组,并通过FileOutputStream将其转换回mp3文件。
但是,我有两个问题。首先,程序运行良好,但是服务器转换的最终mp3文件是一个空文件,仅包含1个字节,而FileOutputStream接收和使用的字节数组不为空。我知道当我的服务器试图将字节数组转换回 mp3 时一定有问题,因为只使用 FileOutputStream 似乎太容易了,我可能误解了它的功能,所以我想知道如何正确地从套接字接收字节数组。
其次,我尝试比较两个程序中的字节数组,发现它们是不同的。一部分是一样的,但大部分是不同的,尤其是字节数组的开头和结尾,我不知道为什么。我对如何从套接字使用 InputStream 和 OutputStream 有概念上的问题吗?
这是发送 mp3 的客户端的部分代码:
public static void sendPackets(){
System.out.println("Sending test file...");
try{
while (active){
File file = new File("Sorrow.mp3"); // Sorrow.mp3 is the local mp3 music needs to be sent
FileInputStream loc = new FileInputStream(file);
sendData = new byte[(int)file.length()];
loc.read(sendData);
//socket_tcp is a Socket object connecting to the server
OutputStream fis = socket_tcp.getOutputStream();
fis.write(sendData);
fis.flush();
fis.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
这是服务器的代码,它接收字节数组并将其转换回mp3:
/** This is the function for the thread listening and receiving the music
* active is a boolean value tracking whether the server is suppose to keep running or not
**/
public static void listen() {
while (active) {
try {
//Wait until packet is received
// listenSocket is a ServerSocket specific for this thread
socket = listenSocket.accept();
System.out.println("We got music from the client!");
File file = new File("Song.mp3");
InputStream is = socket.getInputStream();
receiveData = new byte[1024];
is.read(receiveData);
System.out.println(Arrays.toString(receiveData));
FileOutputStream fos = new FileOutputStream(file);
fos.write(receiveData);
fos.flush();
fos.close();
} catch (IOException e) {
if(active) {
listen();
} else {
break;
}
}
}
我是这个社区的新手,所以如果我在提问时犯了任何错误,请告诉我,谢谢!任何帮助表示赞赏!
【问题讨论】:
标签: java sockets audio tcp client-server