1. 程式人生 > >Java使用udp傳輸方式進行網路通訊

Java使用udp傳輸方式進行網路通訊

需求:通過udp傳輸方式,將一段文字資料傳送出去。
定義一個udp傳送端。
思路:
1,建立udpsocket服務。
2,提供資料,並將資料封裝到資料包中。
3,通過socket服務的傳送功能,將資料包發出去。

4,關閉資源。

import java.net.*;
class  UdpSend
{
	public static void main(String[] args) throws Exception
	{
		//1,建立udp服務。通過DatagramSocket物件。
		DatagramSocket ds = new DatagramSocket(8888);

		//2,確定資料,並封裝成資料包。DatagramPacket(byte[] buf,int length, InetAddress address, int port) 

		byte[] buf = "udp ge men lai le ".getBytes();
		DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000);
		//3,通過socket服務,將已有的資料包傳送出去。通過send方法。
		ds.send(dp);

		//4,關閉資源。

		ds.close();
	}
}

需求:
定義一個應用程式,用於接收udp協議傳輸的資料並處理的。

定義udp的接收端。
思路:
1,定義udpsocket服務。通常會監聽一個埠。其實就是給這個接收網路應用程式

定義數字標識。
方便於明確哪些資料過來該應用程式可以處理。

2,定義一個數據包,因為要儲存接收到的位元組資料。
因為資料包物件中有更多功能可以提取位元組資料中的不同資料資訊。
3,通過socket服務的receive方法將收到的資料存入已定義好的資料包中。
4,通過資料包物件的特有功能。將這些不同的資料取出。列印在控制檯上。
5,關閉資源。

class  UdpRece
{
	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();
	}
}

——摘自《畢向東25天》