天天看點

java UDP傳輸詳解

UDP傳輸是一個面向無連接配接的傳輸方式,什麼叫無連接配接呢,簡單點說呢就是不管你在不線上,我都發資料給你,像那個電影裡警察拿的那個呼叫用的就這這個原理

還有以前的QQ聊天也是,現在2013版的可以選擇是UPD還是TCP,好了不多說,上點代碼玩一下

分析:通過udp傳輸方式,将一段資料發送出去

  思路:

  1,建議udpsocket服務

  2,提供資料,并将資料封裝到資料包中

  3,通過socket服務的發送功能,講資料包發送出去。

  4,關閉資源

牢記思路,代碼哪裡都有

package com.szc02;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

public class UdpSendDemo {

public static void main(String[] args) throws IOException

{

//1,建立udp服務。通過DatagramSocket對象,并且指定一個端口,你也可以不指定

DatagramSocket ds;

try {

ds = new DatagramSocket(10001);

//2,确定資料,并封裝資料包

byte[] buf ="hello UDp ".getBytes();

                               //這裡的ip自己指定

DatagramPacket dp =  

                                new   DatagramPacket(buf,buf.length,InetAddress.getByName("172.16.17.7"),10001);                   

//3,通過socket服務,将已有的資料包發送出去,通過send方法

ds.send(dp);

//4,關閉資源

ds.close();

} catch (SocketException e) {

e.printStackTrace();

}

}

}

 接受資料端:用于接受udp協定傳輸的資料并處理的

 思路:

 1,定義udpsocke服務。通常會監聽一個端口,其實就是給這個接收網絡應用程式 定義一個數字辨別,友善明确哪些資料過來該一個用程式可以處理

 2,定義一個資料包,因為要存儲接收到的位元組資料。 因為資料包對象中有更多的功能可以提取資料中的不同資料資訊。

 3,通過服務的receive方法将收到的資料存入資料包中

 4,通過資料包對象的特有功能,将資料不同的資料取出,列印在控制台上。

 5,關閉資源。

package com.szc02;

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 

   {

//1,建立udpsocket ,建立端口

DatagramSocket ds = null;

try {

ds = new DatagramSocket(10001);

      //循環讀取接資料,注意receive方法是阻塞式的方法,是以這個循環不會是死循環,當沒有讀到資料他就會等待

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();//擷取Ip 位址

String data=new String(dp.getData(),0,dp.getLength());//擷取資料

int port=dp.getPort();//擷取端口

System.out.println(ip+"****"+data+"***"+port);//列印到控制台

}

} catch (SocketException e) {

e.printStackTrace();

}finally{

//5,關閉資源

//ds.close();

}

}

}

記住以上大步驟,這裡其實有很多的異常,我直接抛出去了,主要是講解步驟