我已经为客户端和服务器之间的音频文件(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)行,就像服务器没有收到任何数据包一样。我不知道我在哪里做错了。
答案 0 :(得分:0)
问题出在客户端。
您需要通过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();
}
}
}
当我验证代码时,服务器无法接收来自客户端的所有数据包。我通过在Thread.sleep(10L)
之后添加ds.send(dp)
指令来修复它。