UDP协议中的用法

来源:互联网 发布:淘宝上图片怎么上传 编辑:程序博客网 时间:2024/05/20 12:21

/**创建UDP传输的发送端

*思路:

*1.建立udp的socket服务

*2.将要发送的数据封装到数据包中

*3.通过udp的socket服将数据包发送出去

*4.关闭socket服务

*/

public class Send implements Runnable{

  private DatagramSocket ds;

  

   pubic Send(DatagramSocket ds){

   this.ds = ds;

   }

  

   public void run(){

    try{

      BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

      String line =null;

      while((line=bufr.readLine())!=null){

         byte[] buf = line.getBytes();

         DatagramPacket dp = new      DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),100001);

          ds.send(dp);

         if("886".equals(line))

            break;

            }

           ds.close();

    }catch(Exception e){

    }

     }

}




 /**建立UDP的接受端的思路

*1.建立udp的socket服务,因为是接受数据,必须明确端口号

*2.创建数据包,用于存储接受到的数据,方便用数据包对象的方法解析这些数据

*3.使用socket服务的receive方法将接受到的数据存储到数据包中

*4.通过数据包的方法解析数据包中的数据

*5.关闭资源

*/

public class Rece implement Runnable{

  private DatagramSocket ds;

  public Rece(DatagramSocket ds){

   this.ds = ds;

   }

  public void run(){

    try{

      while(true){

       //传建数据包

        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 text = new String(dp.getData(),0,dp.getLength());

      if(text.equals("886"){

        System.out.println(ip+"...退出聊天");

         }

        }

     }catch(Exception e){}

   }

}



public class ChatDemp{

    public static void main(String[] args)throw IOException{

        DatagramSocket send = new DatagramSocket();

        DatagramSocket rece = new DatagramSocket(100001);

       new Thread(new Send(send)).start();

      new Thread(new Rece(rece)).start();

  }

0 0
原创粉丝点击