// 循环接收数据; import java.net.*; import java.text.SimpleDateFormat; import java.util.Date; import java.io.*; public class XunHuanJS { public static void main(String[] args) throws Exception{ DatagramSocket ds = new DatagramSocket(10004); while(true) { byte[] by = new byte[1024]; DatagramPacket dp = new DatagramPacket(by,by.length); System.out.println("正在接收数据:"); ds.receive(dp); // 获取本地时间 Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分ss秒"); // 调用format方法让模式格式化指对象; String ss = sdf.format(d); System.out.println(ss); String s1 = dp.getAddress().getHostAddress(); // 返回InetAddress对象 再调用getHostAddress方法; String s2 = new String(dp.getData(),0,dp.getLength()); System.out.println(s1+" "+s2); } } }
import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.*; // 循环发送 数据 UDP public class XunHuanFS { public static void main(String[] args) throws Exception{ DatagramSocket ds = new DatagramSocket(); // 通过键盘 录入; BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String lin = null; while((lin=bufr.readLine())!=null) { if("0".equals(lin)) { break; } byte[] by = lin.getBytes(); DatagramPacket dp = new DatagramPacket(by,by.length,InetAddress.getByName("192.168.1.255"),10088); Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分ss秒"); // 调用format方法让模式格式化指对象; String ss = sdf.format(d); System.out.println(ss); ds.send(dp); //发送数据; } ds.close(); // 关闭流; } }