发送方:Demo002Send.java
package com.shsxt.day09.udp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
/*
* 发送方:
* 1、准备一个数据报 发送工具 DatagramSocket
* 2、准备数据
* 3、准备数据报包 (数据+ 地址(ip+端口号))
* 4、发送 (使用数据报发送出数据报包)
* 5、释放资源
*/
public class Demo002Send {
public static void main(String[] args)throws Exception {
DatagramSocket socket = new DatagramSocket(2626);
//byte[] msg = "hello".getBytes();
// 输入数据发送
/*Scanner sc = new Scanner(System.in);
String m = sc.nextLine();
byte[] msg = m.getBytes();*/
// System.in -> 标准输入流
BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
byte[] msg = bis.readLine().getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
InetSocketAddress socketAddress = new InetSocketAddress(address, 3535);
DatagramPacket p = new DatagramPacket(msg, msg.length,socketAddress);
socket.send(p);
socket.close();
DatagramSocket socket1 = new DatagramSocket(5454);
byte[] ms = new byte[1024];
DatagramPacket dp = new DatagramPacket(ms,ms.length);
socket1.receive(dp);
int len = dp.getLength();
System.out.println(new String(ms,0,len));
socket1.close();
}
}
接收方:Demo002Receive
package com.shsxt.day09.udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
/*
* 1、准备一个数据报 接收数据的工具 指定自己在哪个端口接收
* 2、准备接收数据的容器
* 3、准备一个空的数据报包
* 4、接收
* 5、释放资源
*/
public class Demo002Receive {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(3535);
byte[] msg = new byte[1024];
DatagramPacket packet = new DatagramPacket(msg,msg.length);
// 阻塞在此等待数据
socket.receive(packet);
int len = packet.getLength();
String str = new String(msg,0,len);
System.out.println(str);
// 获取发送方信息, 准备回复信息
InetAddress address = packet.getAddress();
InetSocketAddress socketAddress = new InetSocketAddress(address, 5454);
String ms = "来自对方回复:" + str;
DatagramPacket dp = new DatagramPacket(ms.getBytes(),ms.getBytes().length,socketAddress);
socket.send(dp);
socket.close();
}
}