0

我无法将我的 android 客户端连接到我编写的 C 服务器。我发现另一个有类似问题的线程,但不幸的是它被关闭了,说它太窄了。我希望有人可以在这里回答,因为这也与我有关,而且我可以在网上找到的所有示例代码都只有 android 客户端连接到 android 服务器。我的客户端代码如下:

package edu.upenn.seas.cis542;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Try_uiActivity extends Activity
{

//private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "MY IP ADDRESS";
private boolean connected = false;
private Handler handler = new Handler();
final int SERVERPORT = 8080;



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    //NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker3);
    //t1.setRange(1, 5);
    setContentView(R.layout.main);

}

/*
 * When the Submit button is clicked, this method
 * gets called.
 */  


public void onSubmitClick(View view) {



    int item1, item2, item3;

    NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker1);
    item1 = t1.getCurrent();

    NumberPicker t2 = (NumberPicker)findViewById(R.id.numberPicker2);
    item2 = t2.getCurrent();

    NumberPicker t3 = (NumberPicker)findViewById(R.id.numberPicker3);
    item3 = t3.getCurrent();

    String userInput = "" + item1 + item2 + item3;

    //Log.out("Before connecting");

    if (!connected) {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);

            Toast toast=Toast.makeText(this, serverAddr.toString(), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();


            Socket socket = new Socket(serverAddr, SERVERPORT);
            connected = true;
        } catch (Exception e) {
            Toast toast=Toast.makeText(this, "Error2", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

            e.printStackTrace();

            connected = false;
        }
    }
}




}

我省略了连接后我想做的事情,因为仅仅创建套接字已经给我一个错误。我的 C 服务器在 android 程序连接的同一端口上打开一个连接。当我使用 java 客户端文件测试服务器时,它运行良好。有谁知道解决这个问题?我还向 Android Manifest 添加了权限,但这并没有解决问题。谢谢!

4

0 回答 0