其他分享
首页 > 其他分享> > UDP实现消息发送

UDP实现消息发送

作者:互联网

UDP实现消息发送

package com.caster.IP.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception{
    //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
    //2.建立包
        String msg = "你好";
        String msg1 = "为什么收不到字符";
        //发送给谁
        InetAddress address = InetAddress.getByName("localhost");
        int port = 9090;
        //数据 长度 ip 端口
        DatagramPacket packet1 = new DatagramPacket(msg.getBytes(),0,address,port);
        DatagramPacket packet2 = new DatagramPacket(msg1.getBytes(),0,address,port);
    //3.发送包
        socket.send(packet1);
        socket.send(packet2);
    //4.关闭流
        socket.close();

    }
}
package com.caster.IP.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
//还是要等待客户端的连接!
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception{
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffes = new byte[2048];
        DatagramPacket packet = new DatagramPacket(buffes, 0, buffes.length);
        //阻塞接收
        socket.receive(packet);
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0, packet.getLength()));
        System.out.println("--------------");
        socket.close();

    }

}

标签:DatagramSocket,UDP,DatagramPacket,java,socket,packet,发送,消息,new
来源: https://blog.csdn.net/weixin_44199948/article/details/114641980