发送端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class sendMessageUdp {
public static void main(String[] args) throws IOException {
//创建DategramSocket对象(快递公司)
DatagramSocket ds=new DatagramSocket();
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("输入你想要说的话:");
String str=sc.nextLine();
if("886".equals(str)){
break;
}
byte[] buf=str.getBytes();
InetAddress address=InetAddress.getByName("127.0.0.1");
int port=10086;
DatagramPacket dp=new DatagramPacket(buf,buf.length,address,port);
//发送数据
ds.send(dp);
}
//释放资源
ds.close();
}
}
接收端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class recieveMessageUdp {
public static void main(String[] args) throws IOException {
//接收数据
//1.创建DatagramSocket对象(快递公司>//细节:
//在接收的时候,一定要绑定端口
//而且绑定的端口一定要跟发送的端口保持一致
DatagramSocket ds=new DatagramSocket(10086);
//2.接受数据包
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
while(true){
ds.receive(dp);
//3.解析数据包
byte[] data=dp.getData();
int len=dp.getLength();
InetAddress address=dp.getAddress();
int port=dp.getPort();
System.out.println("接收到数据"+new String(buf,0,len));
System.out.println("该数据是从"+address+"这台电脑中的"+port+"端口发出的");
}
}
}
代码运行时先运行接收端,再运行发送端