JAVA UDP发送案例

package Inter;

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;
import java.util.Scanner;

public class UdpSendDemo {
    public static void main(String[] args) throws IOException {
        //创建Socket
       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[] bytes = line.getBytes();
            DatagramPacket dp =  new DatagramPacket(bytes,bytes.length,InetAddress.getByName("127.0.0.1"),10080);
            ds.send(dp);

        }
        ds.close();

    }
}
package Inter;

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

public class UdReceiveDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10080);
        while (true){
            byte[] b = new byte[1024];
            DatagramPacket dp = new DatagramPacket(b,b.length);
            ds.receive(dp);
            String s = new String(dp.getData(), 0, dp.getLength());
            System.out.println("您接收到到是"+s);

        }
    }
}

 

posted @ 2022-04-14 22:40  phpwyl  阅读(34)  评论(0编辑  收藏  举报