1. 程式人生 > 實用技巧 >android。區域網UDP簡單的傳送和接收邏輯

android。區域網UDP簡單的傳送和接收邏輯

傳送

  private DatagramSocket sendSocket = null;

  private int sendPort = 8856;
  private String ip = "192.168.1.100";
   private void sendMsg(final String msg) {
new Thread(new Runnable() {
@Override
public void run() {
try {
if (sendSocket == null) {
sendSocket = new DatagramSocket(sendPort);
}
InetAddress inetAddress = InetAddress.getByName(ip);
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddress, receivePort);
sendSocket.send(datagramPacket);
} catch (Exception e) {
}
}
}).start();
}



接收
private DatagramSocket receiveSocket = null;

private int receivePort = 8855;

DatagramPacket datagramPacket;

private void receiveMsg() {
try {
if (receiveSocket == null) {
receiveSocket = new DatagramSocket(receivePort);
}
while (true) {
byte[] bytes = new byte[1024];
datagramPacket= new DatagramPacket(bytes, 0, bytes.length);
receiveSocket.receive(datagramPacket);
String data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
}
} catch (Exception e) {
}
}