[英]Audio File Transfer using UDP in JAVA
我已經編寫了客戶端和服務器之間的音頻文件(mp3)傳輸代碼。第一台服務器啟動並等待datagrampackets接收,然后客戶端啟動並將UDP數據報包發送到服務器。
\\服務器
serverSocket = new DatagramSocket(4000);
int packetsize=1024;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("zz.wav");
BufferedOutputStream bos = new BufferedOutputStream(fos);
double nosofpackets=Math.ceil(((int) (new File("F:\\nirmal\\1.wav")).length())/packetsize);
byte[] mybytearray = new byte[packetsize];
DatagramPacket receivePacket = new DatagramPacket(mybytearray,mybytearray.length);
System.out.println(nosofpackets+" "+mybytearray+" "+ packetsize);
for(double i=0;i<nosofpackets+1;i++)
{
serverSocket.receive(receivePacket);
byte audioData[] = receivePacket.getData();
System.out.println("Packet:"+(i+1));
bos.write(audioData, 0,audioData.length);
}
\\客戶
File myFile = new File("F:\\nirmal\\1.wav");
DatagramSocket ds=new DatagramSocket(9000);
DatagramPacket dp;
int packetsize=1024;
double nosofpackets;
noofpackets= =Math.ceil(((int) myFile.length())/packetsize);
BufferedInputStream bis;
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));
dp=new DatagramPacket(mybytearray,mybytearray.length,InetAddress.getByName("172.17.13.46"),4000);
}
當客戶端和服務器都運行時,服務器卡在serverSocket.receive(receivePacket)行,就像服務器沒有收到任何數據包。我不知道我在哪里做錯了。
問題出在客戶端。
您需要通過DatagramSocket發送您的DatagramPackets以在服務器端接收。 DatagramScoket是一個客戶端套接字,因此您無需為其保留端口號。 如果您在本地計算機上運行代碼,請更好地使用"localhost"
或"127.0.0.1"
public class UDPClient {
public void send() throws IOException, InterruptedException {
File myFile = new File("aa.hex");
DatagramSocket ds = null;
BufferedInputStream bis = null;
try {
ds = new DatagramSocket();
DatagramPacket dp;
int packetsize = 1024;
double nosofpackets;
nosofpackets = Math.ceil(((int) myFile.length()) / packetsize);
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));
dp = new DatagramPacket(mybytearray, mybytearray.length, InetAddress.getByName("127.0.0.1"), 4000);
ds.send(dp);
}
}finally {
if(bis!=null)
bis.close();
if(ds !=null)
ds.close();
}
}
}
當我驗證代碼時,服務器無法接收來自客戶端的所有數據包。 我通過在ds.send(dp)
之后添加Thread.sleep(10L)
指令來修復它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.