使用UDP協議編寫一個網路程式,設定接收端程式的監聽埠是8001,傳送端傳送的資料是“Hello, world”
阿新 • • 發佈:2019-02-16
import java.net.*; public class UdpC { public static void main(String[] args) throws Exception { DatagramSocket dS=new DatagramSocket(3000); String str="Hello world"; //要傳送的資料 DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(), InetAddress.getByName("localhost"), 8001); dS.send(dp); dS.close(); } }
import java.net.*; public class Udp { public static void main(String[] args) throws Exception { byte[]buf=new byte[1024];//建立一個長度為1024的位元組陣列,用於接收資料 DatagramSocket dS=new DatagramSocket(8001);//設定監聽埠號為8001 DatagramPacket dp=new DatagramPacket(buf,1024); System.out.println("接收資料:"); dS.receive(dp); String str=new String(dp.getData(),0,dp.getLength()); System.out.println(str); dS.close(); } }