zoukankan      html  css  js  c++  java
  • DatagramSocket(UDP协议)

    一、UDP协议无状态协议,不可靠协议,单向通信,数据包

    广播方:

     1 import java.io.IOException;
     2 import java.net.DatagramPacket;
     3 import java.net.DatagramSocket;
     4 import java.net.InetAddress;
     5 import java.sql.SQLException;
     6 
     7 public class Broadcast {
     8 
     9     public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
    10         DatagramSocket ds=new DatagramSocket();
    11         InetAddress address=InetAddress.getByName("123.123.123.123");//输入本服务器IP
    12         byte [] bs="广播一条通知:".getBytes();
    13         DatagramPacket dp=new DatagramPacket(bs, bs.length,address,6666);//端口号自定义
    14         ds.send(dp);
    15         ds.close();
    16     }
    17 }

    听众方:

     1 import java.io.IOException;
     2 import java.net.DatagramPacket;
     3 import java.net.DatagramSocket;
     4 import java.net.InetAddress;
     5 import java.sql.SQLException;
     6 public class UDPClient {
     7 
     8     public static void main(String[] args)  throws IOException{
     9         DatagramSocket ds=new DatagramSocket(6666);
    10         byte[] bs=new byte[65536];
    11         DatagramPacket dp=new DatagramPacket(bs, bs.length);
    12         ds.receive(dp);
    13         String s=new String(dp.getData());
    14         System.out.println("收到的数据为:"+s.substring(0,dp.getLength()/2)+";收到的位移偏量为:"+dp.getOffset()+";有效长度为:"+dp.getLength());
    15         
    16     }
    17 }
  • 相关阅读:
    2017沈阳站 Tree
    P2146 [NOI2015]软件包管理器
    hdu3307 欧拉函数
    poj 3126 Prime Path bfs
    CSL的字符串
    P1045 麦森数
    洛谷 P1338 末日的传说
    树链剖分
    SQL[Err] ORA-00933: SQL command not properly ended
    Postman 快速入门之脚本
  • 原文地址:https://www.cnblogs.com/janesyf/p/7850592.html
Copyright © 2011-2022 走看看