黑马程序员技术交流社区

标题: 用UDP发送和接受数据 [打印本页]

作者: zhao1991    时间: 2015-8-24 15:48
标题: 用UDP发送和接受数据
发送端:
class  UdpSender
{
public static void main(String[] args)  throws Exception
{
  //1 创建发送端Socket,通过创建DatagramSocket对象来实现。
  DatagramSocket datagramSockets= new DatagramSocket(4567);
  //2 生成要发送的数据,并将其封装成数据包,即建立DatagramPacket对象。
  byte[] buffer = "hello,hao are you?".getBytes();
  DatagramPacket dp = new DatagramPacket(bufffer,bufffer.length,InetAddress.getByName("192.168.33.254"),10000);
  //3 通过send方法,将已有的数据包发送出去。
  ds.send(dp);
  //4 关闭资源。
  ds.close();
}
}

接收端:
class  UdpReceiver
{
public static void main(String[] args) throws Exception
{
  //1,创建 Socket,建立端点。
  DatagramSocket ds = new DatagramSocket(10000);
  while(true)
  {
  //2建立缓冲区,用于接受数据报中收到的数据。
  byte[] buf = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf,buf.length);
  //3,通过Socket的receive方法将收到数据存入数据包中。
  ds.receive(dp);//阻塞式方法。
  
  //4,通过数据包的方法获取其中的数据。
  String ip = dp.getAddress().getHostAddress();
  String data = new String(dp.getData(),0,dp.getLength());
  int port = dp.getPort();
  System.out.println(ip+"::"+data+"::"+port);
  }
  //5,关闭资源
  //ds.close();
}
}
PS: 要先启动接收端,以免发送端的数据丢失






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2