package com.myh.practice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class Send {
public static void main(String[] args) throws SocketException {
// DatagramSocket datagramSocket = new DatagramSocket();
// 创建一个字符缓冲输入流,可以获取整行数据
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//创建一个发送端的socket对象
DatagramSocket datagramSocket = null;
/* Scanner scanner = new Scanner(System.in);
System.out.println("请输入消息");
String s = scanner.nextLine();*/
try{
datagramSocket=new DatagramSocket();
String line=null;
while((line=bufferedReader.readLine())!=null){
//自定义结束条件
if("886".equals(line)){
break;
}
//创建数据报包
DatagramPacket datagramPacket = new DatagramPacket(
line.getBytes(),
line.getBytes().length,
InetAddress.getByName("192.168.43.115"),
10012
);
//发送数据
datagramSocket.send(datagramPacket);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(datagramSocket!=null){
datagramSocket.close();
}
}
}
}
package com.myh.practice;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receive {
public static void main(String[] args) {
try {
System.out.println("等待接收");
DatagramSocket datagramSocket = new DatagramSocket(10012);
while(true){
//创建接收端的socket对象
//创建数据报包,接收容器
DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], new byte[1024].length);
//接收
datagramSocket.receive(datagramPacket);
//准备解析真实数据
String s = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
String hostAddress = datagramPacket.getAddress().getHostAddress();
System.out.println("data from:"+hostAddress+"and content is"+s);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}