1. 程式人生 > >Udp Send(傳送端)與Receive(接收端) 基本原理

Udp Send(傳送端)與Receive(接收端) 基本原理

package com.mth.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/*
 *		UdpSend
 *	需求:通過udp傳輸方式 將一段文字資料傳送出去
 *	步驟:
 *	1.建立udpsocket服務
 *	2.提供資料 並將資料封裝到資料包中
 *	3.通過socket服務傳送功能將資料包傳送出去  
 *	4.關閉資源
 * */
public class UdpSend {
	public static void main(String[] args) throws Exception {
		// 1。建立socket服務 通過DatagramSocket物件
		DatagramSocket ds = new DatagramSocket(8888);//指定用8888埠傳送

		// 2.確定資料,並封裝成資料包 通過DatagramPacket物件
		String str = "你好 ";
		byte[] buf = str.getBytes();
		DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress
				.getByName("127.0.0.1"), 10000);

		// 3.通過socket服務 將已有的資料包傳送出去 通過send()方法
		ds.send(dp);
		
		// 4.關閉資源
		ds.close();
	}
}
package com.mth.udp;

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

/*
 *		UdpReceive
 *	需求:定義一個應用程式 用於接收Udp協議傳輸的資料並處理的
 * 	步驟:
 * 	1.定義udpsocket服務 通常會監聽一個埠  確實就是給這個接收網路應用程式定義數字標識
 * 		方便與明確哪些資料過來該應用資料可以處理。
 * 	2.定義一個數據包 因為要儲存接收到的自己資料
 * 		因為資料包物件中有更多功能可以提取自己資料中的不同資料資訊;
 * 	3.通過sockt服務receive()方法存入已定義的資料包中
 * 	4.通過資料包物件的特有功能 將這些不同的資料取出 列印在控制檯上
 * 	5.關閉資源
 * 
 * */

public class UdpReceive {

	public static void main(String[] args) throws Exception {
		// 1.建立udp socket服務,建立端點
		DatagramSocket ds = new DatagramSocket(10000);
		
		
		while (true) {
			// 2.定義資料包
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf, buf.length);

			// 3.通過服務的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();

	}
}