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) {
}
}




posted @ 2020-11-12 14:59  hjy11593219  阅读(241)  评论(0编辑  收藏  举报