JAVA-UDP的簡單運用
阿新 • • 發佈:2018-12-16
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Base64; public class Server { public static void main(String[] args) throws Exception { //建立UDP伺服器物件 DatagramSocket ds = new DatagramSocket(5555); //建立資料包 byte[] bs = new byte[64]; DatagramPacket dp = new DatagramPacket(bs, bs.length); //使用伺服器物件接收資料 放進資料包中 ds.receive(dp); byte[] bs2 = dp.getData();//64 byte[] bs3 = Base64.getDecoder().decode(bs2); System.out.println(new String(bs3)); } }
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.Inet4Address; import java.util.Base64; public class Client { public static void main(String[] args) throws Exception { //建立客戶端物件 DatagramSocket socket = new DatagramSocket(); //建立資料包 byte[] bs = "{type:001,content:你好嗎?}".getBytes(); byte[] bs2 = new byte[64]; //拷貝資料 for (int i = 0; i < bs.length; i++) { bs2[i] = bs[i]; } //空的地方填充0 for (int i = bs.length; i < 64; i++) { bs2[i] = 0; } //加密 String string = Base64.getEncoder().encodeToString(bs2); DatagramPacket dp = new DatagramPacket(string.getBytes(), 64,Inet4Address.getLocalHost(),5555); //傳送資料包 socket.send(dp); } }