UDP 發送與接收數據

//UDP 發送端
package liu.net.udp;

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

public class Send2 {
	public static void main(String[] args) throws IOException {
		/*UDP 發送步驟
		 *1. 創建DatagramSocket 
		 *2. 創建 DatagramPacket
		 *3. 使用 DatagramSocket 的send 方法 發送數據
		 *4. 關閉 DatagramSocket
		 */
		//定義發送使用的端口,接收的IP地址
		try {
			DatagramSocket ds = new DatagramSocket(8899);
			String str = "發送給UDP的數據";
			byte[] buf = str.getBytes();
			InetAddress ip = InetAddress.getByName("127.0.0.1");
			DatagramPacket dp = new DatagramPacket(buf,buf.length,ip,8890);
			ds.send(dp);
			ds.close();
		} catch (SocketException e) {
			e.printStackTrace();
		}							
	}

}



//UDP 接收端

package liu.net.udp;

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

public class Receive2 {
	public static void main(String[] args) throws IOException {
		/*UDP接收步驟:
		 * 使用 DatagramSocket(int port) 創建socket(套間字)服務。(咱們注意到此服務便可以接收,又能夠發送),port指定監視接受端口。
		 *定義一個數據包(DatagramPacket),儲存接收到的數據,使用其中的方法提取傳送的內容
		 *經過DatagramSocket 的receive方法將接受到的數據存入上面定義的包中
		 *使用DatagramPacket的方法,提取數據。
		 *關閉資源。
		 */
		
		//1.使用 DatagramSocket(int port) 創建socket(套間字)服務。
		//	(咱們注意到此服務便可以接收,又能夠發送),port指定監視接受端口。
		DatagramSocket ds = new DatagramSocket(8890);
		
		//2.定義一個數據包(DatagramPacket),儲存接收到的數據,使用其中的方法提取傳送的內容
		byte[] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf,0,buf.length);
		
		//3.經過DatagramSocket 的receive方法將接受到的數據存入上面定義的包中
		ds.receive(dp);
		
		//4.使用DatagramPacket的方法,提取數據。
			//獲取接收的數據。數據報包也包含發送方的 IP 地址和發送方機器上的端口號。 
		String receiveData = new String(dp.getData(),0,dp.getLength());
		String sourceAddress = dp.getAddress().getHostAddress();
		int sourcePort = dp.getPort();
		System.out.println("原地址:"+sourceAddress+"  發送端端口號:"+sourcePort);
		System.out.println("收到的數據內容:"+receiveData);
		
		//5.關閉資源。
		ds.close();		
	}
}
相關文章
相關標籤/搜索