数学建模社区-数学中国

标题: 分布式通信-tcp/ip 广播 [打印本页]

作者: 杨利霞    时间: 2020-5-13 15:16
标题: 分布式通信-tcp/ip 广播
分布式通信-tcp/ip 广播3 U) F' t+ x3 K2 J  P' K1 X. d) M

! h1 i: o" s# X! a. M& k

服务端

/** *  广播 */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();        }    }}
# c7 B) }7 _( p9 A3 P+ I! g

客户端,可以同时有多个客户端

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();        }    }}) h$ A5 F9 N0 |

1 n: u( I/ d$ k* e5 Q: w( {+ P
: C, g2 y1 W' P

转载于:https://www.cnblogs.com/newlangwen/p/10383850.html


8 P! I4 Z' c8 E/ ^. h! n% _
, a  N0 J* E3 R; n9 `  T




欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5