发送
package cn.stat.p4.ipdemo; 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.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; public class netdemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //建立socket对像 System.out.println("发送启动"); senddata(); } //发送数据 public static void senddata() throws SocketException, UnknownHostException, IOException { DatagramSocket ds=new DatagramSocket(); BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in)); String line=null; while((line=bfr.readLine())!=null) { //封装要发送的数据 if(line.equals("over")) break; byte[] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.1.104"), 1000); //通过udp发送 ds.send(dp); } ds.close(); } //获得本机ip public static void getip() throws UnknownHostException { InetAddress ip =InetAddress.getLocalHost(); System.out.println(ip.getHostAddress()); } }
接收
package cn.stat.p4.ipdemo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class jieshoudemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { while(true){ jieshou(); } } public static void jieshou() throws SocketException, IOException { System.out.println("接受启动"); //建立接收socket DatagramSocket ds= new DatagramSocket(1000); //创建数据包 byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf, buf.length); //使用接收方法将数据存储到数据包中 ds.receive(dp); //通过数据包解析获取其中数据,如地址,端口,数据内容 String ip=dp.getAddress().getHostAddress(); int port=dp.getPort(); String txt=new String(dp.getData(),0,dp.getLength()); System.out.println(ip+":"+port+":"+txt); ds.close(); } }
时间: 2024-10-10 10:25:05