Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送
發(fā)短信:不用連接,但需要知道對(duì)方的地址,客戶端、服務(wù)端沒有明確的界限,可以說沒有客戶端、服務(wù)端一說。
發(fā)送端
package lesson03;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;/** * 發(fā)送端 */public class UdpClientDemo1 { public static void main(String[] args) throws Exception { //1、建立一個(gè) Socket DatagramSocket socket = new DatagramSocket(); /** * 2、建個(gè)包 */ //需要發(fā)送的消息 String msg = '你好啊,服務(wù)器!'; //發(fā)送地址 InetAddress localhost = InetAddress.getByName('localhost'); //主機(jī) //發(fā)送端口 int port = 9090; /** * 五個(gè)參數(shù): * @param buf msg.getBytes():需要發(fā)送的數(shù)據(jù)包 * @param offset 0:數(shù)據(jù)偏移量 * @param length msg.getBytes().length:數(shù)據(jù)長(zhǎng)度 * @param address localhost:目標(biāo)地址 * @param port port:目標(biāo)端口 */ DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port); //3、發(fā)送包 socket.send(packet); //4、關(guān)閉流 socket.close(); }}
接收端
package lesson03;import java.net.DatagramPacket;import java.net.DatagramSocket;/** * 接收端 */public class UdpServerDemo1 { public static void main(String[] args) throws Exception { //開放端口 DatagramSocket socket = new DatagramSocket(9090); //接收數(shù)據(jù)包 byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length); //接收 socket.receive(packet); //阻塞接收 //輸出數(shù)據(jù)包地址 System.out.println(packet.getAddress().getHostAddress()); /** * 輸出數(shù)據(jù)包數(shù)據(jù) * packet:Data 類型 * 通過構(gòu)造器轉(zhuǎn)成 String 類型:new String(); */ System.out.println(new String(packet.getData(), 0, packet.getLength())); //關(guān)閉連接 socket.close(); }}
以上就是Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送的詳細(xì)內(nèi)容,更多關(guān)于Java 消息發(fā)送的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用ajax跨域調(diào)用springboot框架的api傳輸文件2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字3. idea右鍵沒有java class選項(xiàng)問題解決方案4. 通過python調(diào)用adb命令對(duì)App進(jìn)行性能測(cè)試方式5. Python查詢oracle數(shù)據(jù)庫速度慢的解決方案6. python新手學(xué)習(xí)可變和不可變對(duì)象7. JS中map和parseInt的用法詳解8. vue中關(guān)于checkbox使用的問題9. python 實(shí)現(xiàn)mysql自動(dòng)增刪分區(qū)的方法10. Python matplotlib畫圖時(shí)圖例說明(legend)放到圖像外側(cè)詳解
