套接字Android客户端

时间:2015-04-23 19:56:30

标签: java android sockets client

我在Java上做了一个TCP客户端并且工作正常,但是当我将类导入到我的Android项目时,它不起作用。

Android代码:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

我总是收到“ERROR OCURRED”消息,我尝试使用其他IP,但所有这些都适用于Java而不是Android。

班级代码:

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

    Button button = (Button) findViewById(R.id.SEND);
    ssid = (EditText) findViewById(R.id.textSsid);
    pass = (EditText) findViewById(R.id.textPass);
    debugText = (EditText) findViewById(R.id.debugText);

    cliente = new ClienteTCP();
    debugText.setText("Version 1-prealpha");

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

public void demo(View view) {

    cliente.configure(ssid.getText(), pass.getText());

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

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

我认为这可能是由于我的模拟器,任何想法?代码错了吗?

编辑:服务器代码:

private CharSequence SSID, pass;
private String HOST = "52.28.45.92"; // My external server i tried with localhot server too ...
// of course i have a server aplication running hahaha
private int PORT = 5000;

private Socket s;
private DataOutputStream oms;

// ...
public CharSequence sendMessage(String ms) {
    DataInputStream ims;
    CharSequence data = null;

    try {
        s = new Socket(HOST,PORT);

        oms = new DataOutputStream(s.getOutputStream());
        ims = new DataInputStream(s.getInputStream());

        oms.writeUTF(ms+getFull());
        data = ims.readUTF();

        oms.close();
        ims.close();
        s.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return data;
}

0 个答案:

没有答案