基于UDP的Socket通信
UDP協(xié)議不是一種基于穩(wěn)定連接的協(xié)議,是一種面向數(shù)據(jù)報包的通信協(xié)議,不需要通信雙方建立穩(wěn)定的連接,也沒有所謂服務端和客戶的概念,數(shù)據(jù)報包在傳輸?shù)臅r候不保證一定及時到達,也不能保證數(shù)據(jù)報包的到達順序,但是UDP協(xié)議傳輸效率要遠高于TCP/IP。
以下是一個基于UDP的簡單的消息發(fā)送接收程序。
消息發(fā)送方
1.創(chuàng)建一個數(shù)據(jù)報的網(wǎng)絡通道
1
|
DatagramSocket ds = new DatagramSocket(); |
2.準備需要傳輸?shù)臄?shù)據(jù)
1
|
String msg = "天王蓋地虎,小雞燉蘑菇!!!" ; |
3.將需要發(fā)送的數(shù)據(jù)打包成數(shù)據(jù)報包
1
2
3
4
5
6
|
DatagramPacket packet = new DatagramPacket( msg.getBytes(), //需要被發(fā)送的數(shù)據(jù)的字節(jié)數(shù)組 msg.getBytes().length, //發(fā)送的數(shù)據(jù)長度(字節(jié)數(shù)組長度) InetAddress.getByName( "localhost" ), //接收方的ip 1025 //接收方的端口 ); |
4.發(fā)送數(shù)據(jù)報包
1
|
ds.send(packet); |
5.關閉通道
1
|
ds.close(); |
消息接收方
1.創(chuàng)建一個數(shù)據(jù)報的網(wǎng)絡通道,綁定到指定端口
1
|
DatagramSocket ds = new DatagramSocket(1025); |
2.聲明字節(jié)數(shù)組,用于存儲接收的數(shù)據(jù)
1
|
byte [] b = new byte [ 1024 ]; |
3.準備數(shù)據(jù)報包(空包)
1
|
DatagramPacket packet = new DatagramPacket(b, b.length); |
4.接收數(shù)據(jù)到數(shù)據(jù)報包中
1
|
ds.receive(packet); |
5.將數(shù)據(jù)解析為字符串并輸出
1
2
3
4
5
|
//接受到的數(shù)據(jù)(字節(jié)數(shù)組)實際長度 int len = packet.getLength(); //將字節(jié)數(shù)組轉(zhuǎn)換為字符串 String s = new String(b, 0 , len); System.out.println( "收到的消息:" +s); |
如要進行循環(huán)接收,則將第4、第5步進行無限循環(huán)。
到此這篇關于java網(wǎng)絡之基于UDP的聊天程序示例解析的文章就介紹到這了,更多相關java基于UDP的聊天程序內(nèi)容請搜索服務器之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_45877744/article/details/107743365