作者在 2008-02-16 15:01:38 发布以下内容
发送程序:
import java.net.*;
public class UdpSend
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket();
String str="hello world";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),Inet4Address.getByName("172.16.203.25"),3000);
ds.send(dp);
ds.close();
}
}
接收程序:
import java.net.*;
public class UdpRecv
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket(3000);
byte[] buf=new byte [1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
String strRecv=new String(dp.getData(),0,dp.getLength())+
"from"+
dp.getAddress().getHostAddress()+":"+dp.getPort();
System.out.print(strRecv);
ds.close();
}
}