天天看點

java——UDP發送和接收資料

package com.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
 * 需求: 通過UDP傳輸方式,将一段文字發送出去
 * 1、建立udpScoket服務
 * 2、提供資料,将資料封裝到資料包中
 * 3、通過socket的發送功能,将資料包發送出去
 * 4、關閉資源
 *  * */

public class UDPSend {

    public static void main(String[] args) throws IOException {
        //1、建立socket對象,通過DatagramSocket對象
        DatagramSocket ds = new DatagramSocket();

        //2、确定資料,并封裝成資料包
        byte[]  data = "hello world".getBytes();
        DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), );

        //3、通過scoket服務,将已有的資料發送出去,通過send方法
        ds.send(dp);
        ds.close();
    }
} 
           
package com.socket;

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

/**
 *需求:定義一個英語程式,用于接受UDP協定傳輸的資料,并進行處理
 *
 * 1、定義uspsocket服務。通常會監聽一個端口,其實就是給這個網絡應用程式定義數字辨別,
 * 友善于  明确哪些資料過來該應用程式可以處理。
 * 2、 定義一個資料包,因為要存儲接收到的位元組資料。因為資料包對象中有更多功能   
 * 可以提取位元組資料中的不同資料資訊。
 * 3、通過socket服務的receive方法,将接收的資料存入已定義好的資料包中
 * 4、将資料包對象的特有功能,将這些不同的資料取出
 * 5、關閉資源
 **/
public class UDPRece {
    public static void main(String[] args) throws IOException{
        System.out.println("===========================");
        //1、建立udp socket ,建立端點,并指定固定端口
        DatagramSocket ds = new DatagramSocket();

        //2、定義資料包,用于存儲資料
        byte[] buf = new byte[];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);

        //3、通過服務的receive方法,接收資料并存入資料包中
        ds.receive(dp);

        //4、通過資料包中的方法,擷取其中的資料。
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String data = new String(dp.getData(), , dp.getLength());
        System.out.println("ip = " + ip + ": " + port + ":   " + data);

        //關閉資源
        ds.close();
    }
}