JAVA中UDP 接受與發送資料的初步步驟__java

來源:互聯網
上載者:User

    UDP是一種高速,不需連線的資料交換方式,他的特點是,即使沒有串連到(也不許要串連)接收方也可以封包發送,就像在一個多人使用的步話機環境中,你不知道你的資訊是否被需要的人接受到,但是你的資訊確實被傳遞然後消失了,有時候速度比資料完整性重要,在比如視頻會議中,丟失幾幀畫面是可以接受的。但在需要資料安全接受的環境就不適用了。


發送步驟: 使用 DatagramSocket(int port) 建立socket(套間字)服務。 將資料打包到DatagramPacket中去 通過socket服務發送 (send()方法) 關閉資源

import java.io.IOException;import java.net.*;public class Send {public static void main(String[] args)  {DatagramSocket ds = null;  //建立套間字udpsocket服務try {  ds = new DatagramSocket(8999);  //執行個體化套間字,指定自己的port} catch (SocketException e) {System.out.println("Cannot open port!");System.exit(1);}byte[] buf= "Hello, I am sender!".getBytes();  //資料InetAddress destination = null ;try {destination = InetAddress.getByName("192.168.1.5");  //需要發送的地址} catch (UnknownHostException e) {System.out.println("Cannot open findhost!");System.exit(1);}DatagramPacket dp = new DatagramPacket(buf, buf.length, destination , 10000);  //打包到DatagramPacket類型中(DatagramSocket的send()方法接受此類,注意10000是接受地址的連接埠,不同於自己的連接埠。)try {ds.send(dp);  //發送資料} catch (IOException e) {}ds.close();}}


接收步驟:
使用 DatagramSocket(int port) 建立socket(套間字)服務。(我們注意到此服務即可以接收,又可以發送),port指定監視接受連接埠。 定義一個資料包(DatagramPacket),儲存接收到的資料,使用其中的方法提取傳送的內容 通過DatagramSocket 的receive方法將接受到的資料存入上面定義的包中 使用DatagramPacket的方法,提取資料。 關閉資源。
import java.net.*;public class Rec {public static void main(String[] args) throws Exception {DatagramSocket ds = new DatagramSocket(10000);  //定義服務,監視連接埠上面的傳送埠,注意不是send本身連接埠byte[] buf = new byte[1024];//接受內容的大小,注意不要溢出DatagramPacket dp = new DatagramPacket(buf,0,buf.length);//定義一個接收的包ds.receive(dp);//將接受內容封裝到包中String data = new String(dp.getData(), 0, dp.getLength());//利用getData()方法取出內容System.out.println(data);//列印內容ds.close();//關閉資源}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.