网络编程_UDP协议_发送端与接收端

创建UDP传输的发送端 :

    1.建立udp的socket服务
      2.将要发送的数据封装到数据包中
      3.通过udp的socket服务 将数据包发送出去
      4.关闭socket服务(因为调用了系统的底层资源网卡)

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSendDemo {
    public static void main(String[] args) throws IOException {
        
        System.out.println("发送端启动.......");
        
        //1.udp的socket服务,使用DatagramSocket对象
        DatagramSocket ds = new DatagramSocket();
        
        //2.将要发送的数据封装到数据包中
        String str = "哥们来啦!";
        
        //使用DatagramPacket将数据封装到该对象包中
        byte[] buf = str.getBytes();
        DatagramPacket dp = 
            new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
        
        //通过udp的socket服务将数据包发送出去,使用send方法
        ds.send(dp);
        
        //关闭资源
        ds.close();
        
    }
}

 

建立UDP接收端:

  1.建立udp socket服务,因为要接受数据,所以必须要明确端口号
  2.创建数据包,用于存储接收到的数据,方便用于数据包对象的方法解析这些数据
  3.使用socket服务的receive方法将接收到的数据存储到数据包中,
  4.通过数据包的方法解析数据包中的数据
  5.关闭资源

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPReceiveDemo {

    public static void main(String[] args) throws IOException {
        
        System.out.println("接收端启动.......");
        
            //1.建立udp socket服务
        DatagramSocket ds = new DatagramSocket(10000);
        
        //2.创建数据包,用于存儲接受到到的数据
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        
        //3.使用接收方法将数据存储在数据包中
        ds.receive(dp);//阻塞式的方法,没有数据会等待
        
        
        //4.通过数据包对象的方法,解析其中的数据,比如:地址,端口,数据内容
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String text = new String(dp.getData(),0,dp.getLength());
        
        System.out.println(ip+":"+port+":"+text);
        //5.关闭资源
        ds.close();
    }

}

 

posted @ 2014-03-18 01:25  胡椒粉hjf  阅读(360)  评论(0编辑  收藏  举报