|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

App inventor 2 en español
Cómo programar los teléfonos móviles con Android
mediante App inventor 2 - Juan Antonio Villalpando

-- Tutorial de iniciación de App Inventor 2 en español --

Volver al índice del tutorial

____________________________

299K.- Extensión. UDP. User Datagram Protocol. Chat Texto. WiFi.

com.KIO4_UDP.aix

p299K_UDP_v2.aia

- Mediante esta extensión podemos enviar voz de un móvil a otro utilizando el protocolo UDP.

- Aquí tenemos más información sobre UDP: ../arduino/118B_Wemos_UDP_AppInventor.htm

- Voz por UDP: 299J_extension_Audio_UDP.htm

___________________________
0.- Código de la extensión.

KIO4_UDP.java


package com.KIO4_UDP;
//  ?© Juan Antonio Villalpando 
// http://kio4.com/appinventor/299K_extension_UDP.htm
//  Diciembre 2022.

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.runtime.util.MediaUtil;
import com.google.appinventor.components.runtime.*;

import android.app.Activity;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// Obtener IP
import java.net.SocketException;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.net.Inet4Address;

@DesignerComponent(version = 1,
    description = "Send/Receive UDP. WiFi. GotText needs a Clock component." + 
    "Juan Antonio Villalpando - KIO4.COM ",
    category = ComponentCategory.EXTENSION,
    nonVisible = true,
    iconName = "") 
@SimpleObject(external = true)
@UsesPermissions(permissionNames = "android.permission.INTERNET, android.permission.ACCESS_WIFI_STATE")

public class KIO4_UDP extends AndroidNonvisibleComponent implements Component {
    public static final int VERSION = 1;
    private ComponentContainer container;
	public static final String DEFAULT_GOT_TEXT = "";
	private String got_text = "-";
    private final Activity activity;
	
	InetAddress toAddr;
    int toPort2;
    String text2;
    int fromPort2;
	
	int portToReceive2;
	int sizePacket2;
	DatagramSocket dsocket;

    public KIO4_UDP(ComponentContainer container) {
        super(container.$form());
        this.container = container;
		GotText(DEFAULT_GOT_TEXT);
        activity = (Activity) container.$context();
    }
	
// Obtener el valor.
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public String GotText() {
	return got_text;
}

// Establecer el valor
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = KIO4_UDP.DEFAULT_GOT_TEXT)
@SimpleProperty(description = "This propertie changes with ToReceive block. It needs a Clock component.")
public void GotText(String nuevogotText) {
	this.got_text = nuevogotText;
}

	
////////////////////// ENVIAR PAQUETE  ////////////////////////////////////////////////////////////
@SimpleFunction(description = "Send Packet.")
public void SendPacket(String toIP, int toPort, String text, int fromPort)  { 
toPort2 = toPort;
text2 = text;
fromPort2 = fromPort;
      try {
            toAddr = InetAddress.getByName(toIP);
            } catch (Exception ex) { }

    Thread thread = new Thread(new Runnable(){
     public void run() {
       try {
	DatagramSocket ds = new DatagramSocket(fromPort2);  
    DatagramPacket dp = new DatagramPacket(text2.getBytes(), text2.length(), toAddr, toPort2);  
    ds.send(dp);  
	ds.disconnect();
	ds.close();
	ds = null;
            } catch (IOException e) { }
        }
      });
      thread.start();
}


////////////////////// RECIBIR PAQUETE  ////////////////////////////////////////////////////////////
@SimpleFunction(description = "Text is received in GotText propertie. Use GotText with a Clock component.")	
public void ToReceive(int portToReceive, int sizePacket) {
portToReceive2 = portToReceive;
sizePacket2 = sizePacket;

Thread thread = new Thread(new Runnable(){
       public void run() {
       try {
        dsocket = new DatagramSocket(portToReceive2);
        byte[] buffer = new byte[sizePacket2];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (true) {
            dsocket.receive(packet);
            String aText = new String(buffer, 0, packet.getLength());
			got_text = aText;	
					    activity.runOnUiThread(new Runnable(){
						public void run() {
						TextReceived(got_text);
						}
						  });  
       }
            } catch (IOException e) { }
        }	
      });  
      thread.start();
}

////////////////////////////////////////////////////////////////////////////////////////
@SimpleFunction(description = "Close to receive.")	
public void CloseToReceive() {
	//dsocket.disconnect();
    dsocket.close();
}
////////////////////////////////////////////////////////////////////////////////////////
@SimpleFunction(description = "Get local IP.")
// http://www.java2s.com/example/java-api/java/net/networkinterface/getnetworkinterfaces-0-1.html
public String GetLocalIp() {
    try {
        for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) 
		{
            NetworkInterface intf = en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {ex.printStackTrace(); }
    return null;
}

// Bloques de EVENTOS.
    @SimpleEvent(description = "Got text from ToReceive block.")
    public void TextReceived(String text){
        EventDispatcher.dispatchEvent(this, "TextReceived", text);
    }  
	
}

___________________________
- Ejemplos de app.

- Ejemplo 1.

- Para hacer la primera prueba ejecutamos la aplicación (funciona en MIT Companion). Obtenemos la IP del dispositivo, en mi caso 192.168.1.2

- Escribimos esa IP en "To IP". Establecemos en "To Port" en puerto a donde enviará, en este caso el 3333.

- En "From Port" el puerto desde donde enviará, en esta caso: 3334 (debe ser distinto a "To Port").

- En "This device will...", escribimos el puerto donde recibiremos la información, en este caso: 3333.

- Escribimos un Texto para enviar y lo recibiremos en la misma aplicación.

- En este ejemplo la aplicación se envía y recibe el texto.

- Ejemplo 2. Chat con dos móviles.

- En cada móvil ponemos la IP y el puerto del otro móvil ("To IP" y "To Port"), también establecemos el puerto por que que recibiremos la información.

- Ejemplo 3. Broadcast.

- Si en vez de establecer la IP de un dispositivos, escribimos To IP: 255.255.255.255 se enviará el texto a toda la red, y "entrará" en aquellos dispositivos que tengan activado el puerto 4444 (en este ejemplo).

___________________________
- Diseño.

___________________________
- Bloques.

___________________________
- Comentarios.

- Si queremos enviar texto con acentos, utilizaremos el componente Web con los bloques UriEncode y UriDecode.

- Si en "To Port" ponemos 0, se enviará a un puerto aleatorio cada vez que enviemos un mensaje.

- Si en "To IP" ponemos 255.255.255.255 se enviará en Broadcast, es decir a toda la red local.

- Como hemos visto en ../arduino/118B_Wemos_UDP_AppInventor.htm podemos utilizar esta extensión para enviar información al ESP32 / ESP8266.

- http://www.it.uc3m.es/celeste/docencia/cr/2003/PracticaSocketsUDP/
___________________________

 

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información