标签:
public class Server { public static String GROUP_IP = "239.1.1.1"; public static int LISTEN_PORT = 22345; public static void run() throws UnknownHostException, IOException { System.out.println("server start......."); MulticastSocket multicastSocket = new MulticastSocket(LISTEN_PORT); InetAddress group = InetAddress.getByName(GROUP_IP); multicastSocket.joinGroup(group); byte[] data = new byte[50]; //未填满空间会被0填充,如果数据长度超出数组则超出的数据被忽略 DatagramPacket packet = new DatagramPacket(data, data.length); while (true) { try { multicastSocket.receive(packet); System.out.println(new String(data)+packet.getAddress()+" "+ new SimpleDateFormat("yy-mm-dd - HH:mm:ss").format(new Date())); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "multicast error"); System.exit(1); } } } public static void main(String[] args){ try{ Server.run(); }catch(Exception e){ e.printStackTrace(); } } }
public class Client { public static void run() throws IOException, InterruptedException { System.out.println("client start......."); String name = "ClientID:5"; MulticastSocket multicastSocket = new MulticastSocket();//其实这里使用DatagramSocket发送packet就行 InetAddress group = InetAddress.getByName(Server.GROUP_IP); String msg = "数据 become"+name; byte[] data = msg.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, group, Server.LISTEN_PORT); int count =1; while (true) { try { multicastSocket.send(packet); System.out.println("send ok ["+name+"]-->"+ count ); count++; Thread.sleep(10000); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "multicast error"); System.exit(1); } } } public static void main(String[] args){ try{ Client.run(); }catch(Exception e){ e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/tanhao/p/4251378.html