TCP Client don't work on Android

孤街醉人 提交于 2019-12-24 03:31:06

问题


I make a client in Java, and make some test on Eclipse IDE and work perfectly, on localhost, external server, etc. When I export the code to android, it doesn't work, the server don't receive nothing ...

Class code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * Jose Manuel R---- ----
 * Java version 2.0
 */
public class ClienteTCP {

private CharSequence TCP_HOST = "localhost";
private int TCP_PORT = 5000;

volatile private CharSequence SSID, PASS, SERVER_IP;
volatile private int SERVER_PORT;

final private String START = "START";

// Constructor vacio
public ClienteTCP( ) {

}

// Constructor con argumentos
public ClienteTCP(CharSequence tcp_host, int tcp_port, CharSequence ssid, CharSequence pass, CharSequence ip, int port) {
    this.TCP_HOST = tcp_host;
    this.TCP_PORT = tcp_port;
    this.SSID = ssid;
    this.PASS = pass;
    this.SERVER_PORT = port;
    this.SERVER_IP = ip;
}

// CONF METHODS

public void setServerTCPConf(CharSequence host, int port) {
    setTCP_HOST(host);
    setTCP_PORT(port);
}

public void setApConf(CharSequence ssid, CharSequence pass) {
    setSSID(ssid);
    setPASS(pass);
}

public void setServerConf(CharSequence ip, int port) {
    setSERVER_IP(ip);
    setSERVER_PORT(port);
}

// PUBLIC METHODS

public String configureMC() {

    sendMessage( createMessage("AP="+SSID.toString()+","+PASS.toString().toString()) );
    sendMessage( createMessage("SERVER="+SERVER_IP.toString()+","+SERVER_PORT) );

    return sendMessage( createMessage(START) );
}

public String sendMessage(String msg) {

    String msgRec = null;
    Socket s;

    try {
        s = new Socket(TCP_HOST.toString(), TCP_PORT);

        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        writer.write(msg, 0, msg.length());
        writer.flush();

        msgRec = reader.readLine();

        reader.close();
        writer.close();
        s.close();

    } catch (IOException e) {
        android.util.Log.d("log", e.getMessage());
        // e.printStackTrace();
    }

    return msgRec;
}

// PRIVATE METHODS

private String createMessage(String msg) {

    char _AF = ((char)175);
    char _FA = (char)250;

    return (_AF+msg+_FA);
}

}

MainActivity:

/*

Jose Manuel adad adsasd
TCP client for Android
v1.2-alpha

 */

import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.net.Socket;

public class MainActivity extends ActionBarActivity {

private volatile EditText debugText;

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

    StrictMode.ThreadPolicy policy = new   StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    Button button = (Button) findViewById(R.id.SEND);
    EditText ssid = (EditText) findViewById(R.id.textSsid);
    EditText pass = (EditText) findViewById(R.id.textPass);
    debugText = (EditText) findViewById(R.id.debugText);
    debugText.setText("Version 1-alpha");

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Do something in response to button click
            demo();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void demo() {

    ClienteTCP cliente = new ClienteTCP();

    CharSequence cs = cliente.sendMessage("Hola Mundo");

    if ( cs != null)
        debugText.setText(cs);
    else
        debugText.setText("ERROR OCURRED");
}
}

I'm sorry due to big code, but I'm going to cry ://///


回答1:


If you try to connect to "localhost" from the Android device, it will try to connect to a service on the Android device because, on whatever device you are running, that is the "local host".

Since the service is running on your machine, it needs to be referenced via an IP address that is reachable by the Android device. That means that if the phone/tablet/whatever is connected to your local WiFi, any 192.168.*.* (private network) address should connect just fine but if it's on the public Internet (via a cellular network, for example) then it'll require the public IP address of your machine or of another device, such as a firewall, that will forward the port to your machine on your internal network.




回答2:


Try change TCP_HOST from localhost to 10.0.2.2



来源:https://stackoverflow.com/questions/29847088/tcp-client-dont-work-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!