真正的Android设备和模拟器之间的连接

时间:2013-09-21 20:40:21

标签: android sockets networking android-emulator port

这个问题在这里已经被问了很多次,但是还没有好的答案。所以我只是发布这个问题以及我的进展。我想知道是否有一种方法可以在真实设备和仿真器之间执行套接字编程。

我提到了android开发者页面:http://developer.android.com/tools/devices/emulator.html

在两个Android设备/之间以及两个仿真器之间建立通信。但我无法将数据从Android设备(客户端)发送到模拟器(作为服务器)。它们都连接到同一网络,并且能够相互ping通。

public class ServerActivity extends Activity {

private TextView serverStatus;
private Button Start;
private Button Mark;
private Button Stop;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";

// DESIGNATE A PORT
public static final int SERVERPORT = 6000;

private Handler handler = new Handler();

private ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    serverStatus = (TextView) findViewById(R.id.server_status);

    Start = (Button)findViewById(R.id.start);
    Mark = (Button)findViewById(R.id.mark);
    Stop = (Button)findViewById(R.id.stop);


    //SERVERIP = getLocalIpAddress();

    Thread fst = new Thread(new ServerThread());
    fst.start();


}

public class ServerThread implements Runnable {

    public void run() {
        try {
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Listening on IP: " + SERVERIP +" "+ SERVERPORT);
                    }
                });
                serverSocket = new ServerSocket(SERVERPORT);
                while (true) {
                    // LISTEN FOR INCOMING CLIENTS
                    final Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Connected.");
                        }
                    });

                    try {
                                handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // DO WHATEVER YOU WANT TO THE FRONT END
                                    // THIS IS WHERE YOU CAN BE CREATIVE

                                     Log.d("ServerActivity", "S: Sending command.");
                                     PrintWriter out;
                                    try {
                                        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
                                         // WHERE YOU ISSUE THE COMMANDS
                                        out.println("HeyClient!");
                                        Log.d("ServerActivity", "S: Sent.");

                                        Start.setOnClickListener(new OnClickListener() {

                                            public void onClick(View arg0) {
                                                // TODO Auto-generated method stub
                                                //send click command to start recording to client

                                            }
                                        });

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

                                }
                            });
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error");
                }
            });
            e.printStackTrace();
        }
    }
}

// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return null;
}

@Override
protected void onStop() {
    super.onStop();
    try {
         // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
         serverSocket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}}

和客户端代码:

公共类ClientActivity扩展了Activity {

private EditText serverIp;

private TextView serverCommand;

private Button connectPhones;

private String serverIpAddress = "";

private boolean connected = false;

private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    connectPhones.setOnClickListener(connectListener);
    serverCommand = (TextView)findViewById(R.id.server_commands);

}

private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
};

public class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, 80);
            connected = true;
            while (connected) 
            {
                try {
                    String line = null;
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                     while ((line = in.readLine()) != null) {
                         Log.d("ClientActivity", line);
                         serverCommand.setText(line);

                         if (line == "start")
                         {



                         }
                     }

                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

}

我还设置了端口转发,以将来自端口80的android的传入连接定向到端口6000的模拟器。这是使用telnet完成的。​​

出于某种原因,所有这些似乎都不会使模拟器连接到传入连接。

如果有人可以帮助我,我将非常感激。

致谢:代码来自http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

0 个答案:

没有答案