我正在使用asynctask在客户端(在我的android设备上运行)和服务器(在我的pc上运行)之间建立连接。当我启动应用程序时,我必须点击按钮来连接它们,如果客户端已连接但没有出现,我的服务器pc程序应该会在控制台设备中显示我;我的android客户端没有连接到pc服务器。
Android客户端:
public class MainActivity extends ActionBarActivity {
Button send;
EditText txt;
TextView testo;
String response = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) findViewById(R.id.send);
//txt = (EditText) findViewById(R.id.editText);
testo = (TextView) findViewById(R.id.textView1);
}
class AddStringTask extends AsyncTask<Void, String, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... unused) {
try {
Socket socketClient = new Socket("10.10.0.151",4321); //ipaddress of my pc server
} catch (UnknownHostException e) {
e.printStackTrace();
response = e.toString();
} catch (IOException e) {
e.printStackTrace();
response = e.toString();
}
testo.setText(response);
return (null);
}
@SuppressWarnings("unchecked")
@Override
protected void onProgressUpdate(String... item) {
}
@Override
protected void onPostExecute(Void unused) {
testo.setText(response);
}
}
public void buttonClick(View v){
new AddStringTask().execute();
}
}Pc服务器:
public class Server {
public static Socket connection;
public static void main(String[] args) throws IOException {
System.out.println("Starting server on port number: 4321...");
ServerSocket server = new ServerSocket(4321);
while(true){
System.out.println("Waiting for clients...");
connection = server.accept();
System.out.println("Connected to: "+connection.getInetAddress().getHostAddress());
connection.close();
}
}}
在我的AndroidManifest.xml中,我刚刚添加了
<uses-permission android:name="android.permission.INTERNET"/>如果我在服务器控制台中从pc启动客户端,我看到设备已连接,但在安卓上不能work..why吗?
谢谢
发布于 2015-07-06 10:16:15
最有可能的是android端的ip是错的。使用内网ip,如: 192.168.1.x。这些类型的ip要求您位于同一网络中。我认为您要做的是从网络外部访问服务器,这需要端口转发。
https://stackoverflow.com/questions/27964402
复制相似问题