生活随笔
收集整理的這篇文章主要介紹了
[Java网络编程]UDP通信程序练习
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼如下:
package UdpPracticePack;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;public class SendDemo {public static void main(String[] args
) throws IOException {DatagramSocket ds
= new DatagramSocket();BufferedReader br
= new BufferedReader(new InputStreamReader(System.in
));String line
;while((line
= br
.readLine())!=null){if ("886".equals(line
)){break;}byte[] bys
= line
.getBytes();DatagramPacket dp
= new DatagramPacket(bys
,bys
.length
, InetAddress.getByName("192.168.1.123"),12345);ds
.send(dp
);}ds
.close();}}
package UdpPracticePack;import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;public class ReceiveDemo {public static void main(String[] args
) throws IOException {DatagramSocket ds
= new DatagramSocket(12345);while(true) {byte[] bys
= new byte[1024];DatagramPacket dp
= new DatagramPacket(bys
, bys
.length
);ds
.receive(dp
);System.out
.println("數(shù)據(jù)是 " + new String(dp
.getData(), 0, dp
.getLength()));}}
}
總結(jié)
以上是生活随笔為你收集整理的[Java网络编程]UDP通信程序练习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。