我在我的 Google Nexus 平板电脑上运行了一个应用程序4.3 JellyBean
,它连接到server(IP 50.30.233.162)
. 该应用程序无法连接到服务器并将错误消息显示为“主机无法访问”。
我检查了InetAddress.getLocalHost().toString();
应用程序中的 ->,它给出了“ localhost/127.0.0.1
”但设备的实际 IP 是“ 50.20.32.225
”
我也给了权限
<uses-permission android:name="android.permission.INTERNET/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE/>
我真的被困住了,任何帮助都会很棒。
公共类 MainActivity 扩展 Activity {
Socket socket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String serverAddress = "50.30.233.162";
new Connecting().execute(serverAddress);
}
private class Connecting extends AsyncTask<String,Integer,String>{
protected String doInBackground(String... serverAdd) {
String serverAddress = serverAdd[0];
try {
EditText editText = (EditText) findViewById(R.id.edit_message);
editText.setText(InetAddress.getLocalHost().toString());
int serverPort = 5789;
socket = new Socket(serverAddress, serverPort);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
}
这是我的服务器代码
公共类服务器{
/**
* @param args
*/
public static void main(String[] args) {
try {
// TupleSpaceServer tupleServer = new TupleSpaceServer();
ServerSocket server = null;
Socket client = null;
String serverIpAdd = null;
int portAdd;
serverIpAdd = InetAddress.getLocalHost().toString();
String[] serverAdd = serverIpAdd.split("/");
serverIpAdd = serverAdd[1];
portAdd = 5789;
System.out.println("Server is now online");
System.out.println("Server IP Address: " + serverIpAdd);
System.out.println("Port Address: " + portAdd);
server = new ServerSocket(portAdd);
while (true) {
client = server.accept();
System.out.println("Client Connected Address: "
+ client.getInetAddress());
// new Thread(new SessionThread(client, tupleServer)).start();
server.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
服务器现已上线 服务器IP地址:50.30.233.162 端口地址:5789