import java.io.*; import java.net.*; import java.util.*;
public class ReceiverAndSender { ?? ?public static void main(String[] args) { ?? ??? ?try { ?? ??? ??? ?// 创建DatagramPacket对象,用来准备接收数据 ?? ??? ??? ?DatagramSocket ds = new DatagramSocket(8888);
?? ??? ??? ?System.out.println("接收方已打开!"); ?? ??? ??? ?// 接收数据 ?? ??? ??? ?byte[] b = new byte[1024]; ?? ??? ??? ?DatagramPacket dp = new DatagramPacket(b, b.length);ds.receive(dp); ?? ??? ??? ?// 显示接收到的信息 ?? ??? ??? ?String str = new String(dp.getData(), 0,dp.getData().length); ?? ??? ??? ?System.out.println(dp.getAddress().getHostAddress()+"发送的数据为:"+str);
?? ??? ??? ?ds.close();
?? ??? ??? ?// 发送回应 ?? ??? ??? ?// 获取本地主机地址 ?? ??? ??? ?InetAddress ia = InetAddress.getLocalHost();
?? ??? ??? ?Scanner can = new Scanner(System.in);
?? ??? ??? ?// 创建DatagramSocket对象,向接收方发送数据 ?? ??? ??? ?DatagramSocket ds2;
?? ??? ??? ?System.out.println("请输入你的回应:"); ?? ??? ??? ?String str2 = can.next(); ?? ??? ??? ?// 创建DatagramPacket对象,封装数据 ?? ??? ??? ?DatagramPacket dp2 = new DatagramPacket(str2.getBytes(), str2.getBytes().length, ia, 8889); ?? ??? ??? ?ds2=new DatagramSocket(); ?? ??? ??? ?ds2.send(dp2);
?? ??? ??? ?// 关闭DatagramSocket对象 ?? ??? ??? ?ds2.close(); ?? ??? ?} catch (SocketException e) { ?? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} catch (IOException e) { ?? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} ?? ?} }
import java.io.*; import java.net.*; import java.util.*;
public class SenderAndReceiver { ?? ?public static void main(String[] args) { ?? ??? ?try { ?? ??? ??? ?// 获取本地主机地址 ?? ??? ??? ?InetAddress ia = InetAddress.getLocalHost(); ?? ??? ??? ?Scanner input = new Scanner(System.in); ?? ??? ??? ?System.out.println("请输入要咨询的问题:"); ?? ??? ??? ?String str = input.next(); ?? ??? ??? ?// 创建DatagramPacket对象,封装数据 ?? ??? ??? ?DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, ia, 8888); ?? ??? ??? ?// 创建DatagramSocket对象,向接收方发送数据 ?? ??? ??? ?DatagramSocket ds = new DatagramSocket(); ?? ??? ??? ?ds.send(dp); ?? ??? ??? ?// 关闭DatagramSocket对象 ?? ??? ??? ?ds.close(); ?? ??? ??? ?// 接收数据 ?? ??? ??? ?byte[] b = new byte[1024]; ?? ??? ??? ?DatagramPacket dp2 = new DatagramPacket(b, b.length); ?? ??? ??? ?// 准备接收回应 ?? ??? ??? ?DatagramSocket ds2 = new DatagramSocket(8889); ?? ??? ??? ?ds2.receive(dp2); ?? ??? ??? ?System.out.println("对方已回答:"); ?? ??? ??? ?// 显示接收到的信息 ?? ??? ??? ?String str2 = new String(dp2.getData(), 0, dp2.getData().length); ?? ??? ??? ?System.out.println(dp2.getAddress().getHostAddress() + "的回答:" + str2); ?? ??? ?} catch (UnknownHostException e) { ?? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} catch (SocketException e) { ?? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} catch (IOException e) { ?? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} ?? ?} }
|