zoukankan      html  css  js  c++  java
  • 网络编程—代码—UDP数据报传输

    UDP:数据报传输

    1、接收端 

    public class Udps { //接收端 
    
    public static void main(String[] args) throws IOException { 
    
    //1.准备接收数据报的箱子
    
    byte[] by = new byte[1024];
    
    DatagramPacket dp = new DatagramPacket(by,by.length); 
    
    //2创建套接字,绑定到相应的端口去接收数据报
    DatagramSocket ds = new DatagramSocket(8803); 
    
    //3.接收数据报
    ds.receive(dp); 
    
    //4.处理操作接收到的数据4属性
    System.out.println(new String(dp.getData(),0,dp.getLength())+dp.getPort()+dp.getSocketAddress()); 
    
    //5.准备反馈的信息,及基本属性
    String replay = "我是服务器,欢迎登录!";
    SocketAddress ia = dp.getSocketAddress(); 
    
    //6将要发送的数据装箱
    DatagramPacket dpr = new DatagramPacket(replay.getBytes(),replay.getBytes().length,ia); 
    
    //7.发送信息
    ds.send(dpr); 
    //8.关闭套接字 ds.close(); } }

    2、发送端

    public class Udpc { //发送端
    
    public static void main(String[] args) throws IOException {
    
    //1准备要发送的数据内容
    String send = "我是客户端,我请求登录!";
    
    //2创建装箱包
    DatagramPacket dp = new DatagramPacket(send.getBytes(),send.getBytes().length,InetAddress.getLocalHost(),8803);
    
    //3创建套接字端口发送数据报
    DatagramSocket ds = new DatagramSocket();
    
    //4.发送数据
    ds.send(dp);
    
    //5准备接受返回的信息
    byte[] by = new byte[1024];
    
    //6.准备接受的装箱的包
    DatagramPacket dpr =new DatagramPacket(by,by.length); 
    
    //7接受信息
    ds.receive(dpr); 
    
    //8处理接受到的信息4属性
    System.out.println(new String(dpr.getData(),0,dpr.getLength())+dpr.getPort()+dpr.getSocketAddress());
    
    //关闭套接字
    ds.close();
    
    }
    
    }
  • 相关阅读:
    简明Python3教程 12.问题解决
    简明Python3教程 11.数据结构
    【SPOJ 694】Distinct Substrings
    【codeforces Manthan, Codefest 17 C】Helga Hufflepuff's Cup
    【CF Manthan, Codefest 17 B】Marvolo Gaunt's Ring
    【CF Manthan, Codefest 17 A】Tom Riddle's Diary
    【SPOJ 220】 PHRASES
    【POJ 3261】Milk Patterns
    【POJ 3294】Life Forms
    【POJ 1226】Substrings
  • 原文地址:https://www.cnblogs.com/domi22/p/8046892.html
Copyright © 2011-2022 走看看