发短信:不用连接,需要知道对方的地址
发送消息
package com.sean.base.netStudy;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
/**
* 不需要链接服务器
* @create 2021-03-01 9:54
*/
public class UdpClientDemo01 {
public static void main(String[] args)throws Exception {
//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.sean.base.netStudy;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.Buffer;
/**
*
* @create 2021-03-01 10:00
*/
public class UdpServerDemo01 {
public static void main(String[] args)throws Exception {
//开放端口
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();
}
}