zoukankan      html  css  js  c++  java
  • java Socket Udp

    接收端:

    package cn.itcast.net.p2.udp;

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;

    public class UDPReceDemo2 {

     /**
      * @param args
      * @throws IOException
      */
     public static void main(String[] args) throws IOException {

      System.out.println("接收端启动......");
      /*
       * 建立UDP接收端的思路。
       * 1,建立udp socket服务,因为是要接收数据,必须要明确一个端口号。
       * 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据.
       * 3,使用socket服务的receive方法将接收的数据存储到数据包中。
       * 4,通过数据包的方法解析数据包中的数据。
       * 5,关闭资源
       */
      
      //1,建立udp socket服务。
      DatagramSocket ds = new DatagramSocket(10000);
      
      while(true){
      
      //2,创建数据包。
      byte[] buf = new byte[1024];
      DatagramPacket dp = new DatagramPacket(buf,buf.length);
      
      //3,使用接收方法将数据存储到数据包中。
      ds.receive(dp);//阻塞式的。
      
      //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
      String ip = dp.getAddress().getHostAddress();
      int port = dp.getPort();
      String text = new String(dp.getData(),0,dp.getLength());
      
      System.out.println(ip+":"+port+":"+text);
      
      
      }
      //5,关闭资源。
    //  ds.close();
      
      
     }
     

    }

    发送端:

    package cn.itcast.net.p2.udp;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;

    public class UDPSendDemo2 {

     /**
      * @param args
      * @throws IOException
      */
     public static void main(String[] args) throws IOException {

      System.out.println("发送端启动......");
      /*
       * 创建UDP传输的发送端。
       * 思路:
       * 1,建立udp的socket服务。
       * 2,将要发送的数据封装到数据包中。
       * 3,通过udp的socket服务将数据包发送出去。
       * 4,关闭socket服务。
       */
      //1,udpsocket服务。使用DatagramSocket对象。
      DatagramSocket ds = new DatagramSocket(8888);
      
      
    //  String str = "udp传输演示:哥们来了!";
      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.100"),10000);
       ds.send(dp);
       
       if("886".equals(line))
        break;
      }
      
      //4,关闭资源。
      ds.close();
      
      
     }

    }

  • 相关阅读:
    NHibernate 使用点滴
    看了二十四画生的文章才发现ASP.NET Portal Starter Kit中调整顺序的一个Bug
    闲话静态构造函数
    ASP.NET Portal starter Kit 之页面配置文件
    VB智能中文提示的一个小工具 VBCommenter 1.2.5
    61条面向对象设计的经验原则
    asp.net Portal Starter kit改造Portal的Html文本编辑器
    Wrox出版社的 Professional DotNetNuke Asp.NET Portals [E文版] 电子书的下载地址
    asp.net Datagrid 资源
    C#与vb.net的区别
  • 原文地址:https://www.cnblogs.com/flying607/p/3442931.html
Copyright © 2011-2022 走看看