发短信:不需要连接,但需要对方的地址
发送端
//不需要连接服务器 public class UdpClientDemo1 { 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, 9090); //3.发送包 socket.send(packet); //4.关闭流 socket.close(); } } 接收端
//还是要等待客户端的连接 public class UdpServerDemo1 { 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()); System.out.println(new String(packet.getData(),0,packet.getLength()));//信封装的是byte类型,我们读的话需要用String来转换 //关闭连接 socket.close(); } }