TCP客户端无法在Android上运行

时间:2015-04-24 12:04:46

标签: java android sockets client

我用Java创建一个客户端,并在Eclipse IDE上进行一些测试并在localhost,外部服务器等上完美地工作。 当我将代码导出到android时,它不起作用,服务器什么都没有收到......

班级代码:

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

由于代码很大,我很抱歉,但我会哭://///

2 个答案:

答案 0 :(得分:1)

如果您尝试从Android设备连接到“localhost”,它将尝试连接到Android设备上的服务,因为在您运行的任何设备上,这是“本地主机”。

由于服务正在您的计算机上运行,​​因此需要通过Android设备可访问的IP地址进行引用。这意味着如果手机/平板电脑/任何连接到本地WiFi的地址,任何192.168。*。*(private network)地址应该连接正常,但如果它在公共互联网上(例如通过蜂窝网络) )然后它将需要您的机器或其他设备(例如防火墙)的公共 IP地址,它将forward the port发送到您内部网络上的计算机。

答案 1 :(得分:0)

尝试将TCP_HOST从localhost更改为10.0.2.2