zoukankan      html  css  js  c++  java
  • java udp 简单例子

    java udp 接收数据

    package udp;

    import java.io.IOException;

    import java.net.DatagramPacket;

    import java.net.DatagramSocket;

    import java.net.SocketException;

    public class UDPReceive {

    public static void main(String[] args){   

      Integer port = 2345;   

      byte[] buffer = new byte[2048];   

      try {    

        DatagramSocket datagramSocket = new DatagramSocket(port);    

        DatagramPacket datagramPacket = new DatagramPacket(buffer,    buffer.length);    

        try {     

          for (int i=0;i<3;i++) {     

          System.out.println("begin receive data....");     

          datagramSocket.receive(datagramPacket);     

          System.out.println(datagramPacket.getAddress().getAddress().toString()+"======="+new String(datagramPacket.getData()));     

          datagramPacket.setLength(datagramPacket.getData().toString().length());   

         }    

        } catch (IOException e) {     

          e.printStackTrace();    

        }   

      } catch (SocketException e) {   

         e.printStackTrace();   

      }  

      }

    }

    java udp 发送数据

    package udp;

    import java.io.IOException;

    import java.net.DatagramPacket;

    import java.net.DatagramSocket;

    import java.net.InetAddress;

    import java.net.SocketException;

    import java.net.UnknownHostException;

    public class UDPSend {

    public static void main(String[] args) {  

      String str = "abcdefghigklmn......";  

       try {    

        for (int i =0 ;i<1;i++) {     

          DatagramSocket sendSocket = new DatagramSocket();     

          DatagramPacket dataPack = new DatagramPacket(     

          str.getBytes(),str.length(), InetAddress.getByName("127.0.0.1"), new Integer(2345));    

          try {      

            sendSocket.send(dataPack);      

            sendSocket.close();     

          } catch (IOException e) {     

             e.printStackTrace();     

          }    

        }   

      } catch (SocketException e) {   

         e.printStackTrace();   

      } catch (UnknownHostException e) {    

        e.printStackTrace();   

      }  

      }

    }

  • 相关阅读:
    output中的path和publicPath
    CSS3 animation设置图片上下移动
    富文本编辑器UEditor
    日历插件:Bootstrap的datetimepicker插件
    文档流、浮动 、定位的概念【转】
    css position [转]
    css line-height [转]
    div 中 id 和 class使用详解【转】
    js中的require、define、export、import【转】
    js 立即调用函数 IIFE(Immediately Invoked Function Expression) 【转】
  • 原文地址:https://www.cnblogs.com/bailuobo/p/2823284.html
Copyright © 2011-2022 走看看