我一直在服务器/客户端应用程序中工作,需要从在我的计算机上工作的服务器获取时间。
当我尝试在手机中运行此应用程序时,它表示SOCKET未连接。我尝试了一切,但它仍然无法正常工作。
线程正在运行,但套接字没有连接!
我使用的权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
MainActivity.java是:
package com.example.clientehora;
/* imports */
public class MainActivity extends Activity {
Socket socket = new Socket();
String SERVER_IP = "10.215.19.41";
int SERVERPORT = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void ejecutar(View view) {
try {
System.out.println("Hola amigo, si me presionaste! =D" + socket.getInetAddress() + socket.getPort());
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String cadena = br.readLine();
System.out.println("LA CADENA ES: " +cadena);
EditText et = (EditText)findViewById(R.id.fecha);
et.setText(cadena);
br.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
System.out.println("Se ha conectado sin problemas");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
这适用于我通过USB连接到我的Win7 PC(mTimeout是5000):
mSocket = new Socket();
mSocket.setSoTimeout(mTimeout);
mSocket.connect(new InetSocketAddress(SERVER_IP, SERVERPORT), mTimeout);
我在PC上使用此命令获取IP:
InetAddress.getLocalHost().getHostAddress()