zoukankan      html  css  js  c++  java
  • Java Socket例程3 UDP

    UdpSend.java

    复制代码
    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[]){
    DatagramSocket ds = null;
    DatagramPacket dp = null;
    try{
    ds = new DatagramSocket(3000); //实例化一个UDP的套接字并绑定3000绑定
           }catch(SocketException e){
    }
    String str = "hello world";
    try{
    dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),9000);
       }
    catch(UnknownHostException ex1){
    }
    try{
    ds.send(dp); //发送数据到本机的9000
    }catch(IOException e){
    }
    ds.close();
    }
    }
    复制代码
    UdpReceive.java
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;


    public class UdpReceive {
        public static void main(String args[]){
            DatagramSocket ds = null; //创建一个套接字对象
            byte[] buf = new byte[1024]; //实例化一个数组
            DatagramPacket dp = null; //创建一个套接字结构对象
            try{
                ds = new DatagramSocket(9000);//实例化并绑定端口       
            }
            catch(IOException e){
               
            }
           
            dp = new DatagramPacket(buf,1024);
            try{
                ds.receive(dp);//接收数据并存放在dp中
            }
            catch(IOException e2){
               
            }
            String str = new String(dp.getData(),0,dp.getLength()) +" from " +dp.getAddress().getHostAddress()+":"+dp.getPort();
            System.out.println(str); //打印接收到的内容
            ds.close();
        }
    }
  • 相关阅读:
    Guava集合-BiMap
    Guava 集合框架
    Guava 学习计划
    解决Gmail/GCalendar图标丢失问题
    Spring cloud系列之win10 下安装 ZooKeeper 的方法
    Spring cloud系列之Zuul配置项中sensitiveHeaders和ignoredHeaders
    Spring Cloud系列之客户端请求带“Authorization”请求头,经过zuul转发后丢失了
    错误:this is incompatible with sql_mode=only_full_group_by
    码云插件Gitee:Couldn't get the list of Gitee repositories
    Redis开发规范
  • 原文地址:https://www.cnblogs.com/wangtingyi/p/4766243.html
Copyright © 2011-2022 走看看