android - 尝试通过 wifi 从 android 连接到桌面服务器时出现问题

标签 android sockets wifi

我正在尝试将文件从运行 Android 1.5 的手机发送到桌面服务器。我写了一些代码,可以在模拟器上运行,但在手机上却不行。我正在通过 WiFi 连接到网络。它有效,我可以通过我的手机访问互联网并且我已经配置了我的路由器。当我尝试连接时应用程序停止。我有权限。有人有任何想法,下面是我的代码。

在安卓上运行

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;
     }

    }

在桌面上运行

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);
               }
          }
     }

}

提前致谢。

最佳答案

您可能知道,您为工作站提供了一个内部 IP 地址 172.20.0.189。您的 Android 设备在通过路由器连接时是否可以看到该地址可能取决于您的路由器设置,以及工作站如何/是否连接到同一路由器。

如果您发布故障发生前后的 logcat 输出,这也会很有用。

关于android - 尝试通过 wifi 从 android 连接到桌面服务器时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2553002/

相关文章:

由公共(public)热点引起的 HTTP 重定向

java - "Unable to get provider com.google.firebase.provider.FirebaseInitProvider"Android路径错误

sockets - lua socket 多次接收报告相同的数据

java - 使用 JAXB 从套接字解码 xml 后客户端被阻止

java简单服务器客户端程序

android - Wi-Fi Direct 和 "normal"Wi-Fi - 不同的 MAC?

linux - 在SDIO接口(interface)中如何注册中断

Android应用程序支持除android之外的所有平台

android - 您需要为您的 APK 使用不同的版本代码,因为您已经有一个版本代码为 1 的 APK。如何更改版本?

android - 无法从 fragment 内部访问公共(public)类的方法