/
SoRusV
/
src_xendil
Обзор
Документация
Войти
/
SoRusV
/
src_xendil
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Android/MUdp.java
109 строк
4 KB
ruslan
Initial commit
29 окт 2024, 11:18
29 окт 2024, 11:18
5c4dcf5
Код
Авторство
О чём код?
package com.example.scord.scord; import android.content.Context; import android.net.DhcpInfo; import android.net.wifi.WifiManager; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import static android.content.Context.WIFI_SERVICE; import static java.net.InetAddress.getByAddress; public class MUdp extends Thread { private BroadcastListener listener; private Context ctx; private DatagramSocket socket; private static final int PORT = 10888; public MUdp(Context ctx, BroadcastListener listener) throws IOException { this.listener = listener; this.ctx = ctx; } public void send(String msg) throws IOException { Log.v("TAGW", "Send "+ msg); DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); byte[] sendData = msg.getBytes(); DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, getBroadcastAddress(), PORT); clientSocket.send(sendPacket); } @Override public void run() { Log.v("TAGW", "MUdp::run()"); socket=null; try { socket = new DatagramSocket(PORT); } catch (SocketException e) { e.printStackTrace(); return; } WifiManager wifiManager = (WifiManager) ctx.getSystemService(WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); byte[] byteaddr = new byte[]{ (byte) (ipAddress & 0xff), (byte) (ipAddress >> 8 & 0xff), (byte) (ipAddress >> 16 & 0xff), (byte) (ipAddress >> 24 & 0xff) }; InetAddress addr=null; try{ addr=InetAddress.getByAddress(byteaddr); }catch(IOException e){ e.printStackTrace(); } while ( socket!=null && !socket.isClosed()) { try { byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); if(!packet.getAddress().equals(addr)) { // Log.v("TAGW", "======recive======"+packet.getAddress().getHostAddress()); listener.onReceive( new String(packet.getData(), 0, packet.getLength()), packet.getAddress().getHostAddress()); } } catch (IOException e) { e.printStackTrace(); } } if(socket!=null) socket.close(); } public void end() { if(socket!=null) socket.close(); } public interface BroadcastListener { public void onReceive(String msg, String ip); } InetAddress getBroadcastAddress() throws IOException { WifiManager wifi = (WifiManager) ctx.getSystemService(WIFI_SERVICE); DhcpInfo dhcp = wifi.getDhcpInfo(); if(dhcp == null) return InetAddress.getByName("255.255.255.255"); int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; byte[] quads = new byte[4]; for (int k = 0; k < 4; k++) quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); Log.v("TAGW", "Adr="+ getByAddress(quads).toString()); return getByAddress(quads); } }