网络通信UDP之发送数据2

package Net.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
 *UDP协议收发数据的注意事项
 *  端口号错误,数据可以整除发出,不会出现异常,但是收不到数据
 *
 * Exception in thread "main" java.net.BindException: Address already in use: Cannot bind
 *  端口号已经绑定,当两个接收端同时运行同一个端口时发生的异常
 * */
public class ReceiveDemo2 {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket(8888);
        byte[] bys=new byte[1024];
        DatagramPacket dp=new DatagramPacket(bys,bys.length);

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

        System.out.println(data);
    }
}

删除线格式

package Net.UDP;

import java.io.IOException;
import java.net.*;

public class SendDemo2 {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket();

        String s="java";
        DatagramPacket dp=new DatagramPacket
                (s.getBytes(),s.length(), InetAddress.getByName("DESKTOP-QG1LSJ2"),9999);

        ds.send(dp);
        ds.close();

    }
}

你可能感兴趣的:(网络通信UDP之发送数据2)