分布式通信-tcp/ip 广播
8 q$ W/ W8 p" l3 |! X9 }* D6 x% p: s: V& n, c
服务端 /** * 广播 */public class MulticastServer { public static void main(String[] args) { try { //地址是224.0.0.0 --239.255.255.255 InetAddress group = InetAddress.getByName("225.0.0.0"); MulticastSocket socket = new MulticastSocket(); for(int i=0;i<10;i++){ String data ="hello world"; byte[] bytes = data.getBytes(); socket.send(new DatagramPacket(bytes,bytes.length,group,8888)); System.out.println("send data"); TimeUnit.SECONDS.sleep(2); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}1 K% q1 d \( v- o
客户端,可以同时有多个客户端 public class MulticastClient { public static void main(String[] args) { //地址是224.0.0.0 --239.255.255.255 try { InetAddress group = InetAddress.getByName("225.0.0.0"); MulticastSocket socket = new MulticastSocket(8888); socket.joinGroup(group); // 加到指定的組裡面 byte[] buf = new byte[256]; while (true){ DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); //读不到一直处于阻塞状态 socket.receive(msgPacket); System.out.println("receive data"); String msg = new String(msgPacket.getData()); System.out.println("接收到的数据:"+msg); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
8 i/ j3 B, M7 Y9 f8 F" s# O6 G
/ R4 R" j/ E5 z4 J! |5 O0 u: W% u: J4 I# |* q& B m
转载于:https://www.cnblogs.com/newlangwen/p/10383850.html
, l! s9 ~& y5 S
9 U/ l2 {1 r K$ @4 d |