Android socket programming without WIFi connection

I have written an app to start my server at home remotely. The app works without problems in the emulator and also on my smartphone (HTC desire, Android 2.2) when WiFi is enabled. However it does not work when WiFi is disabled.

Before restarting I first check if it's already running. To do this I use sockets and I first connect to a dyndns address. After that I try to connect to my ip-box where I can switch on my computer by sending commands via a socket.

When the connection to that socket fails I know the server is not running.

The relevant code is:

        socket = new Socket();
        socket.connect(new InetSocketAddress(serverName, port), 10000);
            status = socket.isConnected() == true;
        socket.close();

If there's an exception (SocketException) I know that the server is not running. This approach works perfectly when I have switched WiFi on. However if WiFi's not switched on then the connect always says it's ok, even if it could not establish a connection since the server is not available.

Is there a way to check if the the connection is really established, even if WiFi is disabled?

Any suggestions welcome!

Thanks,

Rudi


Try to open your socket like this :

public boolean connect(String ip, int port) {
    try {
        this.clientSocket = new Socket(ip, port);
        clientSocket.setSoTimeout(timeout);
        this.outToServer = new DataOutputStream(clientSocket
                .getOutputStream());
        this.inFromServer = clientSocket.getInputStream();
        isconnected = true;
    } catch (IOException e) {
        Log.e("TCPclient", "connection failed on " + ip + ":" + port);
        isconnected = false;
        return isconnected;
    }
    Log.e("TCPclient", "connection to " + ip + " sucessfull");
    return isconnected;
}

If connection is not successful , it will generate an IOException (work when wifi enabled and no server , and when wifi is not enabled(HTC desire 2.3)).
This code is not really correct ,it's just a short version

EDIT Try to check wfi state like this (it is not practical but it should work)

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ConnectivityManager cm = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      if (ni.isConnected()) {
        Toast.makeText(this,"Wifi enabled", Toast.LENGTH_LONG).show();  
        Log.d("WiFiStateTestActivity", "WiFi!");
      } else {
        Toast.makeText(this,"Wifi not enabled", Toast.LENGTH_LONG).show();  
        Log.d("WiFiStateTestActivity", "not WiFi!");
      }
    }

不要忘记在manifest.xml中设置权限以允许您打开套接字。

链接地址: http://www.djcxy.com/p/10290.html

上一篇: 这两种背包算法是一样的吗? (他们总是输出相同的东西)

下一篇: 没有WIFi连接的Android套接字编程