Java網絡編程UDP協議發送接收數據
本文實例為大傢分享瞭Java網絡編程UDP協議發送接收數據的具體代碼,供大傢參考,具體內容如下
UDP協議發送數據步驟
A:創建發送端socket對象;
B:創建數據,並把數據打包;
C:調用socket對象的發送方法發送數據包;
D:釋放資源
package net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendDemo { public static void main(String[] args) throws IOException { //A DatagramSocket ds = new DatagramSocket(); //B byte[] by = "Hello,UDP".getBytes(); int length = by.length; InetAddress addr = InetAddress.getByName("192.168.1.22"); int port = 10010; DatagramPacket dp = new DatagramPacket(by, length, addr, port); //C ds.send(dp); //D ds.close(); } }
UDP協議接收數據步驟
A:創建接收端socket對象;
B:創建一個數據包(接收容器);
C:調用socket對象的接收方法接收數據;
D:解析數據,顯示到控制臺;
E:釋放資源
package net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ReceiveDemo { public static void main(String[] args) throws IOException { //A DatagramSocket ds = new DatagramSocket(10010); //B byte[] by = new byte[1024]; int length = by.length; DatagramPacket dp = new DatagramPacket(by, length); //C ds.receive(dp); //D //獲取對方ip InetAddress addr = dp.getAddress(); String ip = addr.getHostAddress(); byte[] by2 = dp.getData(); int len = by2.length; String s = new String(by2, 0, len); System.out.println(ip+"發送的數據是:"+s); //E ds.close(); } }
先運行接收端代碼,再運行發送端代碼。
多次從鍵盤接收發送數據版本
package net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendDemo { public static void main(String[] args) throws IOException { //A DatagramSocket ds = new DatagramSocket(); //數據來自鍵盤錄入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; while((line = br.readLine()) != null){ //當輸入jieshu時,結束 if("jieshu".equals(line)){ break; } //B byte[] by = line.getBytes(); int length = by.length; InetAddress addr = InetAddress.getByName("192.168.1.22"); int port = 10010; DatagramPacket dp = new DatagramPacket(by, length, addr, port); //C ds.send(dp); } //D ds.close(); } }
package net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ReceiveDemo { public static void main(String[] args) throws IOException { //A DatagramSocket ds = new DatagramSocket(10010); //多次接受版本 while(true){ //B byte[] by = new byte[1024]; int length = by.length; DatagramPacket dp = new DatagramPacket(by, length); //C ds.receive(dp); //D //獲取對方ip InetAddress addr = dp.getAddress(); String ip = addr.getHostAddress(); byte[] by2 = dp.getData(); int len = by2.length; String s = new String(by2, 0, len); System.out.println(ip+"發送的數據是:"+s); } //E //ds.close(); } }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。