Problem when trying to connect to a desktop server from android on wifi

Posted by thiagolee on Stack Overflow See other posts from Stack Overflow or by thiagolee
Published on 2010-03-31T12:54:36Z Indexed on 2010/03/31 13:03 UTC
Read the original article Hit count: 292

Filed under:
|
|

Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code.

Running on Android

package br.ufs.reconhecimento;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

/**
 * Sample code that invokes the speech recognition intent API.
 */
public class Reconhecimento extends Activity implements OnClickListener {

    static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    static final String LOG_VOZ = "UFS-Reconhecimento";
    final int INICIAR_GRAVACAO = 01;
    int porta = 5158; // Porta definida no servidor
    int tempoEspera = 1000;
    String ipConexao = "172.20.0.189";
    EditText ipEdit;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.main);

        // Get display items for later interaction
        ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak);
        speakButton.setPadding(10, 10, 10, 10);

        speakButton.setOnClickListener(this);

        //Alerta para o endereço IP
        AlertDialog.Builder alerta = new AlertDialog.Builder(this);
        alerta.setTitle("IP");//+mainWifi.getWifiState());

        ipEdit =  new EditText(this);
        ipEdit.setText(ipConexao);
        alerta.setView(ipEdit);
        alerta.setMessage("Por favor, Confirme o endereço IP.");
        alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
                    ipConexao = ipEdit.getText().toString();
                    Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } });
        alerta.create();
        alerta.show();

    }


    /**
     * Handle the click on the start recognition button.
     */
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            //startVoiceRecognitionActivity();
          Log.d(LOG_VOZ, "Iniciando a próxima tela");
          Intent recordIntent = new Intent(this, GravacaoAtivity.class);
          Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)");
          startActivityForResult(recordIntent, INICIAR_GRAVACAO);
          Log.d(LOG_VOZ, "Gravação iniciada ...");
        }
    }


    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     Log.d(LOG_VOZ, "Iniciando onActivityResult()");
     if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) {
          String path = data.getStringExtra(GravacaoAtivity.RETORNO);
          conexaoSocket(path);
     }
     else
          Log.e(LOG_VOZ, "Resultado Inexperado ...");
    }

    private void conexaoSocket(String path) {
     Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera);
     if(socket == null)
          return;
     try {
               DataOutputStream conexao = new DataOutputStream(socket.getOutputStream());
               Log.d(LOG_VOZ, "Acessando arquivo ...");
               File file = new File(path);
               DataInputStream arquivo = new DataInputStream(new FileInputStream(file));
               Log.d(LOG_VOZ, "Iniciando Transmissão ...");
               conexao.writeLong(file.length());
               for(int i = 0; i < file.length(); i++)
                    conexao.writeByte(arquivo.readByte());
               Log.d(LOG_VOZ, "Transmissão realizada com sucesso...");
               Log.d(LOG_VOZ, "Fechando a conexão...");
               conexao.close();
               socket.close();
               Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso ==============");
          } catch (IOException e) {
               Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage());
               // TODO Auto-generated catch block
          }
    }

}

    class SocketOpener implements Runnable {

     private String host;
     private int porta;
     private Socket socket;

     public SocketOpener(String host, int porta) {
          this.host = host;
          this.porta = porta;
          socket = null;
     }

     public static Socket openSocket(String host, int porta, int timeOut) {

          SocketOpener opener = new SocketOpener(host, porta);
          Thread t = new Thread(opener);
          t.start();
          try {
               t.join(timeOut);
          } catch(InterruptedException e) {
               Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage());
               //TODO: Mensagem informativa
               return null;
          }
          return opener.getSocket();
     }

     public void run() {
          try {
               socket = new Socket(host, porta);

          }catch(IOException e) {
               Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage());
               //TODO: Mensagem informativa
          }
     }

     public Socket getSocket() {
          return socket;
     }

    }

Running on the desktop

Java:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ServidorArquivo {

     private static int porta = 5158;

     static String ARQUIVO = "voz.amr";
     /**
      * Caminho que será gravado o arquivo de audio
      */
     static String PATH = "/home/iade/Trabalho/lib/";

     public static void main(String[] args) {

          int i = 1;
          try {
               System.out.println("Iniciando o Servidor Socket - Android.");
               ServerSocket s = new ServerSocket(porta);
               System.out.println("Servidor Iniciado com Sucesso...");
               System.out.println("Aguardando conexões na porta: " + porta);
               while(true) {
                    Socket recebendo = s.accept();
                    System.out.println("Aceitando conexão de nº " + i);
                    new ThreadedHandler(recebendo).start();
                    i++;
               }
               } catch (Exception e) {
                    System.out.println("Erro: " + e.getMessage());
                    e.printStackTrace();
               }
     }

}

class ThreadedHandler extends Thread {

     private Socket socket;

     public ThreadedHandler(Socket so) {
          socket = so;
     }

     public void run() {

          DataInputStream entrada = null;
          DataOutputStream arquivo = null;
          try {

               entrada = new DataInputStream(socket.getInputStream());
               System.out.println("========== Iniciando a leitura dos dados via Sockets ==========");
               long tamanho = entrada.readLong();
               System.out.println("Tamanho do vetor " + tamanho);
               File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO);
               if(!file.exists())
                    file.createNewFile();

               arquivo = new DataOutputStream(new FileOutputStream(file));
               for(int j = 0; j < tamanho; j++) {
                    arquivo.write(entrada.readByte());
               }
               System.out.println("========== Dados recebidos com sucesso ==========");

          } catch (Exception e) {
               System.out.println("Erro ao tratar do socket: " + e.getMessage());
               e.printStackTrace();
          } finally {
               System.out.println("**** Fechando as conexões ****");
               try {
                    entrada.close();
                    socket.close();
                    arquivo.close();
               } catch (IOException e) {
                    System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage());
                    e.printStackTrace();
               }

          }
          System.out.println("============= Fim da Gravação ===========");

          // tratar o arquivo

          String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav";
          String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100";
          String dir = "/home/iade/Trabalho/lib";
          File workDir = new File(dir);
          File f1 = new File(dir+"/voz.wav");
          File f2 = new File(dir+"/voz2.wav");
          f1.delete();
          f2.delete();

          try {
               executeCommand(cmd1, workDir);
               System.out.println("realizou cmd1");
               executeCommand(cmd2, workDir);
               System.out.println("realizou cmd2");

          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }

     }

     private void executeCommand(String cmd1, File workDir) throws IOException,
               InterruptedException {
          String s;
          Process p = Runtime.getRuntime().exec(cmd1,null,workDir);
          int i = p.waitFor();
          if (i == 0) {
               BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
               // read the output from the command
               while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
               }
          }
          else {
               BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
               // read the output from the command
               while ((s = stdErr.readLine()) != null) {
                    System.out.println(s);
               }
          }
     }

}

Thanks in advance.

© Stack Overflow or respective owner

Related posts about android

Related posts about wifi