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

UDP消息发送

作者:互联网

UDP

发短信:不用连接,需要知道对方的地址!
发送消息

package com.wang.netStudy.lesson03;

import com.sun.xml.internal.ws.api.message.Packet;

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

//不需要连接服务器
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();
    }
}

接收消息

package com.wang.netStudy.lesson03;


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

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();
    }
}

标签:DatagramSocket,UDP,java,packet,发送,消息,new,import,net
来源: https://www.cnblogs.com/wshjyyysys/p/15860464.html