Java udp簡單通訊__Java

來源:互聯網
上載者:User
/* *通過Udp將文字發送出去 * 提供資料,封裝資料包 * socket發送 * 關閉資源 */class UdpSendDemo {    public static void main(String[] args) throws IOException {        //建立udp服務        DatagramSocket ds = new DatagramSocket();        //確定資料 封裝為資料包        byte[] data = "我是發送端".getBytes();        DatagramPacket dp = new DatagramPacket(data,data.length, InetAddress.getByName("127.0.0.1"),10000);        //發送        ds.send(dp);        //關閉        ds.close();    }

}

/** * 接收udp傳過來的資料 * 定義udpsocket服務 監聽一個連接埠 * 通過socket服務的recive方法將收到的資料存入以定義好的資料包中 * 打出控制台 * 關閉資源 */class UdpReciveDemo {    public static void main(String[] args) throws IOException {        //建立udp socket建立端點        DatagramSocket ds = new DatagramSocket(10000 );        //定義資料包用於儲存資料        byte[] arrPacket = new byte[1024];        DatagramPacket dp = new DatagramPacket(arrPacket,arrPacket.length);        //通過recive方法接收資料存入資料包        ds.receive(dp);        //通過資料包中的方法擷取資料        String ip = dp.getAddress().getHostAddress();        String data = new String(dp.getData(),0,dp.getLength());        int port = dp.getPort();        System.out.println(ip+":"+data+":"+port);        //關閉資源        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.