发送UDP广播

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpUtil {
 /**
  * UDP发送
  *
  * @param message
  *            广播的内容
  * @param port
  *            服务器监听的端口号
  * @param host
  *            PC/服务器端IP地址
  */
 public static void sendMessage(String message, int port, String host) {
  message = (message == null ? "空了" : message);
  DatagramSocket ds = null;
  try {
   ds = new DatagramSocket();
  } catch (SocketException e) {
   e.printStackTrace();
  }
  InetAddress local = null;
  try {
   local = InetAddress.getByName(host);
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
  int msgLength = message.length();
  byte[] messageByte = message.getBytes();
  DatagramPacket dp = new DatagramPacket(messageByte, msgLength, local, port);
  try {
   ds.send(dp);
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   ds.close();
  }
 }
}

你可能感兴趣的:(android开发)