1. 程式人生 > >基於udp協議的Socket通訊案例

基於udp協議的Socket通訊案例

傳送端程式碼

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Main {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        String s = "hello udp,i am coming!";
        byte[] bys = s.getBytes();
        int length = bys.length;
        InetAddress address = InetAddress.getByName("SKY-20180725WBH");
        int port = 7799;
        // DatagramPacket 此類標識資料包
        DatagramPacket dp = new DatagramPacket(bys, length, address, port);
        ds.send(dp);
        ds.close();
    }
}

接收端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Receive {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(7799);
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys, bys.length);
        System.out.println(1);
        ds.receive(dp); //阻塞
        System.out.println(2);

        InetAddress address = dp.getAddress();
        byte[] data = dp.getData();
        int length = dp.getLength();

        System.out.println("send ------>" + address.getHostAddress());
        System.out.println(new String(data, 0, length));


        ds.close();
    }
}

執行效果圖

在這裡插入圖片描述