• 即时通信 (广播)


     1 package Test;
     2 
     3 import java.io.IOException;
     4 import java.net.DatagramPacket;
     5 import java.net.InetAddress;
     6 import java.net.MulticastSocket;
     7 import java.util.Scanner;
     8 
     9 
    10 public class GuangboSrc {
    11 
    12     /**
    13      * @param args
    14      * @throws IOException 
    15      */
    16     public static void main(String[] args) throws IOException {
    17 //        创建广播地址
    18         InetAddress ip=InetAddress.getByName("230.0.0.1");
    19 //        将创建的广播加入到广播组中
    20 
    21         MulticastSocket multicastSocket=new MulticastSocket(55555);
    22         multicastSocket.joinGroup(ip);
    23 //        创建广播的数据包
    24         System.out.println("请输入要广播的内容:");
    25         Scanner scan=new Scanner(System.in);
    26         String str=scan.next();
    27         byte[]b=str.getBytes();
    28         DatagramPacket pancket =new DatagramPacket(b, b.length, ip,55555);
    29 //        发送广播
    30         multicastSocket.send(pancket);
    31     }
    32 
    33 }
    发送端
     1 package Test;
     2 
     3 import java.io.IOException;
     4 import java.net.DatagramPacket;
     5 import java.net.InetAddress;
     6 import java.net.MulticastSocket;
     7 import java.net.UnknownHostException;
     8 
     9 public class GuanagboDes {
    10 //    接受广播
    11     public static void main(String[] args) throws IOException {
    12         // TODO Auto-generated method stub
    13 //        广播地址
    14         InetAddress ip=InetAddress.getByName("230.0.0.1");
    15 //        将广播地址加入到广播组中
    16         MulticastSocket multicastSocket=new MulticastSocket(55555);
    17         multicastSocket.joinGroup(ip);
    18         
    19 //        接收数据报
    20         byte[]b=new byte[1024];
    21         DatagramPacket packet =new DatagramPacket(b,b.length);
    22 //        接受广播
    23         multicastSocket.receive(packet);
    24 //        展示广播内容
    25         String str=new String(packet.getData(),0,packet.getLength());
    26         System.out.println("接受到的广播信息是:"+str);
    27         
    28         
    29     }
    30 
    31 }
    接收端
  • 相关阅读:
    linux网卡eth1如何修改为eth0
    rpm方式安装MySQL5.1.73
    quartz demo01
    chrome 搜索 jsonView
    判断是否十六进制格式字符串
    ip and port check 正则
    hadoop 遇到java.net.ConnectException: to 0.0.0.0:10020 failed on connection
    hadoop2.4.1 伪分布
    R 包
    使用pt-heartbeat检测主从复制延迟
  • 原文地址:https://www.cnblogs.com/xiaoqisfzh/p/4709387.html
Copyright © 2020-2023  润新知