A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© huburt 中级黑马   /  2016-5-28 10:36  /  362 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class SendAndReceive {

  2.         public static void main(String[] args) {
  3.                 // 开启线程用于接收消息
  4.                 new Thread() {
  5.                         public void run() {
  6.                                 try {
  7.                                         receive();
  8.                                 } catch (Exception e) {
  9.                                         e.printStackTrace();
  10.                                 }
  11.                         };
  12.                 }.start();

  13.                 // 主线程发送消息
  14.                 try {
  15.                         send();
  16.                 } catch (Exception e) {
  17.                         e.printStackTrace();
  18.                 }
  19.         }

  20.         public static void send() throws Exception {
  21.                 System.out.println("send执行");
  22.                 DatagramSocket socket = new DatagramSocket();
  23.                 Scanner sc = new Scanner(System.in);
  24.                 while (true) {
  25.                         String line = sc.nextLine();
  26.                         DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length,
  27.                                         InetAddress.getByName("127.0.0.1"), 6666);
  28.                         socket.send(packet);
  29.                         if (line.equals("quit")) {
  30.                                 break;
  31.                         }
  32.                 }
  33.                 socket.close();
  34.                 System.out.println("send结束");
  35.         }

  36.         public static void receive() throws Exception {
  37.                 System.out.println("receive执行");
  38.                 DatagramSocket socket = new DatagramSocket(6666);
  39.                 DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
  40.                 while (true) {
  41.                         socket.receive(packet);
  42.                         byte[] b = packet.getData();
  43.                         int len = packet.getLength();
  44.                         String ip = packet.getAddress().getHostAddress();
  45.                         int port = packet.getPort();
  46.                         String line = new String(b, 0, len);
  47.                         if (line.equals("quit")) {
  48.                                 break;
  49.                         }
  50.                         System.out.println(ip + ":" + port + ":" + line);
  51.                 }
  52.                 socket.close();
  53.                 System.out.println("receive结束");
  54.         }
  55. }
复制代码
您需要登录后才可以回帖 登录 | 加入黑马