2010-11-24 15 views
12

Quiero transferir mensajes desde el dispositivo Android a la aplicación de escritorio. Mi pregunta es si puedo conectar el dispositivo WiFi de Android con el dispositivo WiFi de escritorio sin ningún uso de conexión a Internet. Quiero usarlo como el Bluetooth. ¿Es esto posible o no? si es posible, ¿cómo puedo implementarlo?Conectividad WIFI a WIFI con Android

Gracias y Saludos Amit Thaper

+0

¡Esa pregunta es difícil de leer, por favor revise su formato! –

Respuesta

15

Aquí hay una implementación de la sugerencia de mreichelt. Busqué esto cuando tuve el mismo problema y pensé que simplemente publicaría mi implementación de la solución. es realmente simple. También construí un servidor de Java que escucha las solicitudes entrantes desde el dispositivo Android (para fines de depuración en su mayoría). aquí está el código para enviar cosas por la red inalámbrica:

import java.net.*; 
import java.io.*; 
import java.util.*; 

import android.app.Activity; 
import android.content.Context; 
import android.content.ContentValues; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.util.Log; 


public class SMSConnection { 
     /* The socket to the server */ 
    private Socket connection; 

    /* Streams for reading and writing the socket */ 
    private BufferedReader fromServer; 
    private DataOutputStream toServer; 

    /* application context */ 
    Context mCtx; 

    private static final String CRLF = "\r\n"; 

    /* Create an SMSConnection object. Create the socket and the 
     associated streams. Initialize SMS connection. */ 
    public SMSConnection(Context ctx) throws IOException { 
     mCtx=ctx; 
     this.open(); 
     /* may anticipate problems with readers being initialized before connection is opened? */ 
     fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     toServer = new DataOutputStream(connection.getOutputStream()); 
    } 

    public boolean open(String host, int port) { 
     try { 
      connection = new Socket(host, port); 
      return true; 
     } catch(IOException e) { 
      Log.v("smswifi", "cannot open connection: " + e.toString()); 
     } 
     return false; 
    } 

    /* Close the connection. */ 
    public void close() { 
     try { 
      connection.close(); 
     } catch (IOException e) { 
      Log.v("smswifi","Unable to close connection: " + e.toString()); 
     } 
    } 

    /* Send an SMS command to the server. Check that the reply code 
     is what is is supposed to be according to RFC 821. */ 
    public void sendCommand(String command) throws IOException { 

     /* Write command to server. */ 
     this.toServer.writeBytes(command+this.CRLF); 

     /* read reply */ 
     String reply = this.fromServer.readLine(); 
    } 
} 

que es un esqueleto básico para una clase de conexión. simplemente crea una instancia de la clase y abre la instancia que crea con el host y el puerto (no olvide cerrar la conexión cuando haya terminado) y puede cambiar el cuerpo de sendCommand a su gusto. He incluido una operación de lectura/escritura en el cuerpo de la función como un ejemplo.

aquí está el código para ejecutar un servidor en una máquina remota que escucha las conexiones y engendra un hilo para manejar cada solicitud. puede interactuar fácilmente con el código anterior para la depuración (o cualquier uso).

import java.io.*; 
import java.net.*; 
import java.util.*; 

public final class smsd { 
    ///////MEMBER VARIABLES 
    ServerSocket server=null; 
    Socket client=null; 

    ///////MEMBER FUNCTIONS 
    public boolean createSocket(int port) { 
     try{ 
      server = new ServerSocket(port); 
      } catch (IOException e) { 
      System.out.println("Could not listen on port "+port); 
      System.exit(-1); 
     } 
     return true; 
    } 

    public boolean listenSocket(){ 
     try{ 
      client = server.accept(); 
     } catch (IOException e) { 
      System.out.println("Accept failed: "); 
      System.exit(-1); 
     } 
     return true; 
    } 

    public static void main(String argv[]) throws Exception { 
     // 
     smsd mySock=new smsd(); 

     //establish the listen socket 
     mySock.createSocket(3005); 
     while(true) { 
      if(mySock.listenSocket()) { 
       //make new thread 
       // Construct an object to process the SMS request message. 
       SMSRequest request = new SMSRequest(mySock.client); 

       // Create a new thread to process the request. 
       Thread thread = new Thread(request); 

       // Start the thread. 
       thread.start(); 
      } 
     } 

     //process SMS service requests in an infinite loop 

    } 
///////////end class smsd///////// 
} 


final class SMSRequest implements Runnable { 
    // 
    final static String CRLF = "\r\n"; 
    Socket socket; 

    // Constructor 
    public SMSRequest(Socket socket) throws Exception 
    { 
     this.socket = socket; 
    } 

    // Implement the run() method of the Runnable interface. 
    public void run() 
    { 
     try { 
      processRequest(); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

    private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception 
     { 
      // Construct a 1K buffer to hold bytes on their way to the socket. 
      byte[] buffer = new byte[1024]; 
      int bytes = 0; 

      // Copy requested file into the socket's output stream. 
      while((bytes = fis.read(buffer)) != -1) { 
       os.write(buffer, 0, bytes); 
      } 
     } 

    private void processRequest() throws Exception 
    { 
     // Get a reference to the socket's input and output streams. 
     InputStream is = this.socket.getInputStream(); 
     DataOutputStream os = new DataOutputStream(this.socket.getOutputStream()); 

     // Set up input stream filters. 
     InputStreamReader isr = new InputStreamReader(is); 
     BufferedReader br = new BufferedReader(isr); 

     // Get the request line of the SMS request message. 
     String requestLine = br.readLine(); 

     //print message to screen 
     System.out.println(requestLine); 

     //send a reply 
     os.writeBytes("200"); 

     // Close streams and socket. 
     os.close(); 
     br.close(); 
     socket.close(); 
    } 
} 

nb4namingconventions.

casi lo olvido. Necesitará configurar estos permisos dentro de las etiquetas en su AndroidManifest.xml para usar la conexión inalámbrica.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
2

Esto es fácilmente posible si ambos dispositivos están utilizando la misma red WiFi y pueden ping entre sí. Puede crear una aplicación Java en su escritorio que crea un ServerSocket. Luego puede abrir Socket en su aplicación Android usando la dirección IP del escritorio y enviar datos a través del OutputStream.

2

Creo que Amit se refiere a hacer que las máquinas se conecten entre sí de forma inalámbrica.

Actualmente, se está desarrollando la especificación WiFi directa para permitir la configuración Plug-in-Play de puntos de acceso. El problema actualmente es asegurar que una de las máquinas sea un AP al que otras máquinas puedan establecer conexión.

Me interesa saber cómo se relaciona esto con las redes Ad-Hoc. No tengo una solución, ¡pero estoy muy interesado en esta pregunta también! (Asumiendo que esta es su pregunta Amit).

+0

sí, quiero conectarme de esta forma, como definió Eric. ejemplo para aclarar la respuesta es teléfonos Bluetooth. Quiero emparejar dos dispositivos con Wi-Fi como Bluetooth sin usar ningún enrutador. –

Cuestiones relacionadas