udp接收数据
发布时间: 2024-12-25 05:28:19
A. java 怎么用UDP实时接收数据
我自己写的代码:
importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.DatagramSocket;
importjava.net.InetAddress;
importjava.net.SocketException;
importjava.net.UnknownHostException;
publicclassUdpRecvDemo
{
publicstaticvoidmain(String[]args)throwsIOException
{
Recv();
}
publicstaticvoidRecv()throwsIOException
{
System.out.println("接受开始......");
DatagramSocketds=newDatagramSocket(3388);
while(true)
{
byte[]buf=newbyte[1024];
DatagramPacketdp=newDatagramPacket(buf,buf.length);
ds.receive(dp);
System.out.println(ds);
Stringip=dp.getAddress().getHostAddress();
intport=dp.getPort();
Stringtext=newString(dp.getData(),0,dp.getLength());
if(text.equals("exit"))
{
System.out.println(ip+"退出会话......");
break;
}
System.out.println(ip+":"+port+"===>me"+text);
}
ds.close();
}
}