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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 暗影流光 中级黑马   /  2014-7-12 10:16  /  895 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class TestUDP {

  2.         /**
  3.          * @param args
  4.          * @throws IOException
  5.          */
  6.         public static void main(String[] args) throws IOException {
  7.                 DatagramSocket send = new DatagramSocket();
  8.                 Send s = new Send(send);
  9.                 DatagramSocket rece = new DatagramSocket(10001);
  10.                 Receive r = new Receive(rece);
  11.                 new Thread(s).start();
  12.                 new Thread(r).start();
  13.         }

  14. }
  15. public class Send implements Runnable {
  16.         private DatagramSocket ds;

  17.         Send(DatagramSocket ds) {
  18.                 this.ds = ds;
  19.         }

  20.         @Override
  21.         public void run() {
  22.                 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  23.                 String line = null;
  24.                 try {
  25.                         while ((line = br.readLine()) != null) {
  26.                                 byte[] bys = line.getBytes();
  27.                                 InetAddress in = InetAddress.getLocalHost();
  28.                                 DatagramPacket dp = new DatagramPacket(bys, bys.length, in,
  29.                                                 10001);
  30.                                 ds.send(dp);
  31.                                 if(line.equalsIgnoreCase("over"))
  32.                                         break;
  33.                         }
  34.                 } catch (IOException e) {
  35.                         e.printStackTrace();
  36.                 }
  37.         }
  38. }
  39. public class Receive implements Runnable {
  40.         private DatagramSocket ds;

  41.         Receive(DatagramSocket ds) {
  42.                 this.ds = ds;
  43.         }

  44.         @Override
  45.         public void run() {
  46.                 byte[] bys = new byte[1024];
  47.                 DatagramPacket dp = new DatagramPacket(bys, bys.length);
  48.                 try {
  49.                         while (true) {
  50.                                 ds.receive(dp);
  51.                                 String data=new String(dp.getData(),0,dp.getLength());
  52.                                 System.out.println(dp.getAddress().getHostAddress()+":"+data);
  53.                         }
  54.                 } catch (IOException e) {
  55.                         e.printStackTrace();
  56.                 }
  57.         }

  58. }
复制代码


2 个回复

倒序浏览
一句注释都没有,懒得看了都
回复 使用道具 举报
额 ,提问结束??
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马