Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送
發(fā)短信:不用連接,但需要知道對(duì)方的地址,客戶端、服務(wù)端沒有明確的界限,可以說(shuō)沒有客戶端、服務(wù)端一說(shuō)。
發(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. CSS代碼檢查工具stylelint的使用方法詳解2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. WML語(yǔ)言的基本情況4. 詳解CSS偽元素的妙用單標(biāo)簽之美5. 不要在HTML中濫用div6. div的offsetLeft與style.left區(qū)別7. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂代碼8. 使用css實(shí)現(xiàn)全兼容tooltip提示框9. html清除浮動(dòng)的6種方法示例10. 利用CSS3新特性創(chuàng)建透明邊框三角
