需求: 1.发送数据:数据来自键盘录入,输入886时退出 2.接收数据:时刻准备接受数据,采用死循环
发送端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Send {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line=br.readLine())!=null) {
if("886".equals(line)) {
break;
}
byte[] bys= line.getBytes();
DatagramPacket dp=new DatagramPacket(bys,bys.length,InetAddress.getByName("IP地址"),10086);
ds.send(dp);
}
ds.close();
}
}
接收端
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) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
while(true) {
byte[] bys=new byte[1024];
DatagramPacket dp = new DatagramPacket(bys,bys.length);
ds.receive(dp);
byte[] datas=dp.getData();
System.out.println("数据是:"+new String(datas,0,dp.getLength()));
}
}
}
|