Red en Android LSUB, GYSC, URJC

Red en Android LSUB, GYSC, URJC Red en Android • Igual que en Java • Algunas peculiaridades con el interfaz (WIFI lock) • Se puede emular Cliente public void hola(View button){ int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola", time); msg.show(); Thread c = new Thread(){ @Override public void run() { Socket s; OutputStream o; o = null; try{ s = new Socket("10.0.2.2", 2000); OutputStream o = s.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); } Cliente ! ! } } } } catch (ConnectException e){ System.out.println("connection refused" + e); catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); catch(IOException e){ System.out.println("IO exception" + e); finally { if o != null o.close() } } } }; c.start(); Permisos • Como para muchos recursos hay que pedir permiso al usuario • Se declaran los permisos que se necesitan en el manifest Permisos (cliente o servidor) ! ... Servidor ! try{ ServerSocket s = new ServerSocket(1234); OutputStream o; o = null; while(true){ Socket sin = s.accept(); if(sin == null) break; o = sin.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); } catch(IOException e){ System.out.println("IO exception" + e); } finally { if o != null o.close() } Información de Interfaces • La clase WifiInfo (ojo, en el emulador no funciona). • Necesita el permiso: ! Información de Interfaces WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = String.format("%d.%d.%d.%d", ipAddress & 0xff, ipAddress>>8 & 0xff, ipAddress>>16 & 0xff, ipAddress>>24 & 0xff); int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola soy: " + ip, time); msg.show(); WIFI lock • En cuanto deja de haber actividad se apaga la WIFI (aunque haya conexiones abiertas) • Si no quiero que se me de problemas puedo hacer que se quede encendida • Si el usuario la apaga, se apaga WIFI lock • Mejor por cuenta de referencias • Así, creo uno sólo para mi App y me despreocupo WIFI lock WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , “MyWifiLock”); // Poner cuenta de referencias wifilock.setReferenceCounted(true); // Coger el cierre wifiLock.acquire(); // Usar la red // Coger el cierre wifiLock.release(); Log.i(“Mi_app”, "WiFi Lock released!”); WIFI lock • Tengo que pedir el permiso: ! 3G • Detrás de NAT (en muchas WIFIs también) • Lo mejor es usar un servidor para comunicarse Emular la Red • Todo lo que hay que saber: • http://developer.android.com/tools/devices/ emulator.html#emulatornetworking Depuración • Usar telnet o nc para depurar (se puede redireccionar la entrada y usar una fifo creada con mkfifo) • Así nos fiamos de uno de los lados mientras depuramos el otro Emular la Red Puerto de control Emular la red Simulador 10.0.2.15 Simulador 10.0.2.15 Gateway 1234 10.0.2.1 Gateway 10.0.2.1 325 Host 127.0.0.1 == 10.0.2.2 Las direcciones que ven los emuladores son siempre las mismas Emular la red Redireccionar el puerto del NAT (de entrada al dispositivo) $ telnet localhost 5554 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Android Console: type 'help' for a list of commands OK redir add tcp:325:1234 OK ! Emular la red (servidor) ! try{ ServerSocket s = new ServerSocket(1234); while(true){ Socket sin = s.accept(); if(sin == null) break; OutputStream o = sin.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); o.close(); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); } catch(IOException e){ System.out.println("IO exception" + e); } Depuración (servidor:android, cliente: telnet) $ telnet localhost 1234 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hola hola Connection closed by foreign host. $ Depuración: (cliente:android, servidor: nc) • Es cómodo poner un netcat de servidor para probar • Ej: cliente en el dispositivo, conecta a 10.0.2.2:2000 en la shell ejecuto: $ nc -l 2000 Depuración ! s = new Socket("10.0.2.2", 2000); OutputStream o = s.getOutputStream(); byte buf[] = "hola hola\n".getBytes("UTF-8"); o.write(buf, 0, buf.length); o.close();

6 downloads 14 Views 261KB Size

Story Transcript

Red en Android LSUB, GYSC, URJC

Red en Android • Igual que en Java

• Algunas peculiaridades con el interfaz (WIFI lock)

• Se puede emular

Cliente public void hola(View button){ int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola", time); msg.show(); Thread c = new Thread(){ @Override public void run() { Socket s; OutputStream o; o = null; try{ s = new Socket("10.0.2.2", 2000); OutputStream o = s.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); }

Cliente ! !









} } } }

catch (ConnectException e){ System.out.println("connection refused" + e); catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); catch(IOException e){ System.out.println("IO exception" + e); finally { if o != null o.close()

} }

} }; c.start();

Permisos • Como para muchos recursos hay que pedir permiso al usuario

• Se declaran los permisos que se necesitan en el manifest

Permisos (cliente o servidor)

!



...

Servidor

!

















try{ ServerSocket s = new ServerSocket(1234); OutputStream o; o = null; while(true){ Socket sin = s.accept(); if(sin == null) break; o = sin.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); } catch(IOException e){ System.out.println("IO exception" + e); } finally { if o != null o.close() }

Información de Interfaces • La clase WifiInfo (ojo, en el emulador no funciona).

• Necesita el permiso: !



Información de Interfaces





WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress();









String ip = String.format("%d.%d.%d.%d", ipAddress & 0xff, ipAddress>>8 & 0xff, ipAddress>>16 & 0xff, ipAddress>>24 & 0xff); int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola soy: " + ip, time); msg.show();

WIFI lock • En cuanto deja de haber actividad se apaga

la WIFI (aunque haya conexiones abiertas)

• Si no quiero que se me de problemas

puedo hacer que se quede encendida

• Si el usuario la apaga, se apaga

WIFI lock • Mejor por cuenta de referencias

• Así, creo uno sólo para mi App y me despreocupo

WIFI lock WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , “MyWifiLock”);

// Poner cuenta de referencias wifilock.setReferenceCounted(true);

// Coger el cierre wifiLock.acquire();

// Usar la red // Coger el cierre wifiLock.release(); Log.i(“Mi_app”, "WiFi Lock released!”);

WIFI lock • Tengo que pedir el permiso: !



3G • Detrás de NAT (en muchas WIFIs también)

• Lo mejor es usar un servidor para comunicarse

Emular la Red • Todo lo que hay que saber:

• http://developer.android.com/tools/devices/ emulator.html#emulatornetworking

Depuración • Usar telnet o nc para depurar (se puede redireccionar la entrada y usar una fifo creada con mkfifo)

• Así nos fiamos de uno de los lados mientras depuramos el otro

Emular la Red

Puerto de control

Emular la red Simulador

10.0.2.15

Simulador

10.0.2.15

Gateway

1234 10.0.2.1

Gateway

10.0.2.1

325

Host 127.0.0.1 == 10.0.2.2

Las direcciones que ven los emuladores son siempre las mismas

Emular la red Redireccionar el puerto del NAT

(de entrada al dispositivo) $ telnet localhost 5554

Trying ::1...

telnet: connect to address ::1: Connection refused

Trying 127.0.0.1...

Connected to localhost.

Escape character is '^]'.

Android Console: type 'help' for a list of commands

OK

redir add tcp:325:1234

OK

!

Emular la red (servidor)

!









try{ ServerSocket s = new ServerSocket(1234); while(true){ Socket sin = s.accept(); if(sin == null) break; OutputStream o = sin.getOutputStream(); byte buf[] = "hola hola".getBytes("UTF-8"); o.write(buf, 0, buf.length); o.close(); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(UnknownHostException e){ System.out.println("cannot connect to host " + e); } catch(IOException e){ System.out.println("IO exception" + e); }

Depuración (servidor:android, cliente: telnet)

$ telnet localhost 1234

Trying ::1...

telnet: connect to address ::1: Connection refused

Trying 127.0.0.1...

Connected to localhost.

Escape character is '^]'.

hola hola

Connection closed by foreign host.

$

Depuración: (cliente:android, servidor: nc)

• Es cómodo poner un netcat de servidor para probar

• Ej: cliente en el dispositivo, conecta a 10.0.2.2:2000 en la shell ejecuto: $ nc -l 2000

Depuración !











s = new Socket("10.0.2.2", 2000); OutputStream o = s.getOutputStream(); byte buf[] = "hola hola\n".getBytes("UTF-8"); o.write(buf, 0, buf.length); o.close();

Depuración $ nc -l 2000 hola hola $

Automatización: adb • Para hacerle cosas al emulador

automáticamente desde la shell

• Por ejemplo levantar el interfaz de red y cambiar a 3G, cambiar el forward de puertos, etc.

• http://developer.android.com/tools/help/ adb.html#move

WIFI direct • Conectar dos teléfonos directamente

• Sin access point

• Sin bluetooth (protocolo roto en muchos teléfonos y no llega muy lejos)

Get in touch

Social

© Copyright 2013 - 2024 MYDOKUMENT.COM - All rights reserved.