UDP消息发送

UDP消息发送

UDP消息发送类似于发短信,不用连接,需要知道对方地址

发送端

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

//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1.建立一个socket
        DatagramSocket socket=new DatagramSocket();
        //2.建个包
        String msg="你好啊,郝雨霏";
        InetAddress localhost= InetAddress.getByName("localhost");
        int port=9090;

        //数据,数据的长度起,始,发送对象,端口
        DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //3.发送包
        socket.send(packet);
        //4.关闭流
        socket.close();
    }
}

接收端

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

public class UDPserverDemo01 {
    public static void main(String[] args) throws IOException {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffer=new byte[1024];
        DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);//阻塞接收
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //关闭连接
        socket.close();
    }
}

结果展示:

UDP消息发送

上一篇:网络编程


下一篇:【AVD】用 notepad++ 和 Excel 协助分析媒体文件包