我无法将我的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的权限,但这并没有解决问题。谢谢!