package cn.itcast_04;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
// 建立接收端Socket對象
DatagramSocket ds = new DatagramSocket(12345);
while (true) {
// 建立接收資料包對象
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
// 接收資料包
ds.receive(dp);
// 解析資料,并顯示在控制台
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from" + ip + " data is:" + s);
}
// 釋放資源
// ds.close();
}
}
package cn.itcast_04;
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 SedDemo {
public static void main(String[] args) throws IOException {
// 建立發送端Socket對象
DatagramSocket ds = new DatagramSocket();
// 封裝鍵盤錄入資料
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
// 建立資料,并打包
byte[] bys = line.getBytes();
// DatagramPacket dp = new DatagramPacket(bys, bys.length,
// InetAddress.getByName("192.168.31.165"), 12345);
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("192.168.31.255"), 12345);
// 發送資料
ds.send(dp);
}
// 釋放資源
ds.close();
}
}