UDP 广播 Java
1、服务端
public class UdpBroadcastServer { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int port = 9999;// 开启监听的端口 DatagramSocket ds = null; DatagramPacket dp = null; byte[] buf = new byte[1024];// 存储发来的消息 try { // 绑定端口的 ds = new DatagramSocket(port); dp = new DatagramPacket(buf, buf.length); System.out.println("监听广播端口打开:"); while (true) { ds.receive(dp); int i; StringBuffer sbuf = new StringBuffer(); for (i = 0; i < 1024; i++) { if (buf[i] == 0) { break; } sbuf.append((char) buf[i]); } System.out.println("收到广播消息:" + sbuf.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2、客户端
public class UdpBroadcastClient { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // 广播的实现 :由客户端发出广播,服务器端接收 String host = "255.255.255.255";// 广播地址 int port = 9999;// 广播的目的端口 String message = "test";// 用于发送的字符串 try { InetAddress adds = InetAddress.getByName(host); DatagramSocket ds = new DatagramSocket(); DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length(), adds, port); while (true) { ds.send(dp); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }