java UDP傳輸


①:只要是網絡傳輸,必須有socket 。

②:數據一定要封裝到數據包中,數據包中包括目的地址、端口、數據等信息。

 

直接操作udp不可能,對於java語言應該將udp封裝成對象,易於我們的使用,這個對象就是DatagramSocket. 封裝了udp傳輸協議的socket對象。

 

因為數據包中包含的信息較多,為了操作這些信息方便,也一樣會將其封裝成對象。這個數據包對象就是:DatagramPacket.通過這個對象中的方法,就可以獲取到數據包中的各種信息。

 

DatagramSocket具備發送和接受功能,在進行udp傳輸時,需要明確一個是發送端,一個是接收端。

 

udp的發送端:

①:建立udp的socket服務,創建對象時如果沒有明確端口,系統會自動分配一個未被使用的端口。

②:明確要發送的具體數據。

③:將數據封裝成了數據包。

④:用socket服務的send方法將數據包發送出去。

⑤:關閉資源。

 

udp的接收端:

①:創建udp的socket服務,必須要明確一個端口,作用在於,只有發送到這個端口的數據才是這個接收端可以處理的數據。

②:定義數據包,用於存儲接收到數據。

③:通過socket服務的接收方法將收到的數據存儲到數據包中。

④:通過數據包的方法獲取數據包中的具體數據內容,比如ip、端口、數據等等。

⑤:關閉資源。

 

 

Eg:

發送端(客戶端)

import java.net.*;

class  UdpSend{

        public static void main(String[] args)throws Exception {

                // 1,建立udp的socket服務。

                DatagramSocket ds = new DatagramSocket(8888);//指定發送端口,這個可以不指定,系統會隨機分配。

                // 2,明確要發送的具體數據。

                String text = "udp傳輸演示 哥們來了";

                byte[] buf = text.getBytes();

                // 3,將數據封裝成了數據包。

                DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.1.31.127"),10000);

                // 4,用socket服務的send方法將數據包發送出去。

                ds.send(dp);

                // 5,關閉資源。

                ds.close();

        }

}

 

接收端(服務器端)

 

import java.net.*;

class UdpRece {

        public static void main(String[] args) throws Exception{

                // 1,創建udp的socket服務。

                DatagramSocket ds = new DatagramSocket(10000);//必須指定,並且和上面的端口號一樣!

                // 2,定義數據包,用於存儲接收到數據。先定義字節數組,數據包會把數據存儲到字節數組中。

                byte[] buf = new byte[1024];

                DatagramPacket dp = new DatagramPacket(buf,buf.length);

                // 3,通過socket服務的接收方法將收到的數據存儲到數據包中。

                ds.receive(dp);//該方法是阻塞式方法。

                // 4,通過數據包的方法獲取數據包中的具體數據內容,比如ip,端口,數據等等。

                String ip = dp.getAddress().getHostAddress();

                int port = dp.getPort();

                String text = new String(dp.getData(),0,dp.getLength());//將字節數組中的有效部分轉成字符串。

                System.out.println(ip+":"+port+"--"+text);

                // 5,關閉資源。

                ds.close();

        }

}

 

 

練習:

通過鍵盤錄入獲取要發送的信息。

將發送和接收分別封裝到兩個線程中。

 

package july76net;

//一個聊天的例子,利用UDP傳輸協議

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

 

//客戶端,發送端

class Send implements Runnable {

    private DatagramSocket ds;

 

    public Send(DatagramSocket ds) {

        super();

        this.ds = ds;

    }

 

    @Override

    public void run() {

        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(

                    System.in));//數據源是鍵盤錄入

            String line;

            while ((line = br.readLine()) != null) {

                byte[] buf = line.getBytes();

                DatagramPacket dp = new DatagramPacket(buf, buf.length,

                        InetAddress.getByName("localhost"), 10225);

 

                ds.send(dp);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

 

// 服務器端,接收端

class Rece implements Runnable {

    private DatagramSocket ds;

 

    public Rece(DatagramSocket ds) {

        super();

        this.ds = ds;

    }

 

    @Override

    public void run() {

        try {

            while (true) {

                byte[] buf = new byte[1024];

 

                DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);

                ds.receive(dp);

 

                String ip = dp.getAddress().getHostAddress();

                String data = new String(dp.getData(), 0, dp.getLength());

 

                System.out.println(ip + "     " + data);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

 

public class Demo6 {

    public static void main(String[] args) throws Exception {

        DatagramSocket sendDs = new DatagramSocket();

        DatagramSocket receDs = new DatagramSocket(10225);

        new Thread(new Send(sendDs)).start();

        new Thread(new Rece(receDs)).start();

    }

}

 

輸出:

你好

127.0.0.1     你好

你好

127.0.0.1     你好


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM