Search code examples
javaandroidsocketsnio

SocketChannel is not ready


again i have got a problem with socket programming in Android. My Problem is Selector.select() returns zero that there are no SocketChannels ready for writing. And again the same code works in normal Java but does not work in Android. Here is my code:

package com.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class WebSocketTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

  SocketChannel channel = null;

        SocketAddress socketAdress = new InetSocketAddress("10.0.0.1", 8787);

  try {
   channel = SocketChannel.open();
  } catch (IOException e) {
   Log.e("ERROR", "channel open");
  }

  try {
   channel.configureBlocking(false);
  } catch (IOException e1) {
   Log.e("ERROR", "channel blocking");
  }

  try {
   channel.connect(socketAdress);
  } catch (IOException e) {
   Log.e("ERROR", "channel connect");
  }

  try {
   while(!channel.finishConnect())
   {

   }
  } catch (IOException e1) {
   Log.e("ERROR", "channel finishConnect");
  }


  Selector selector = null;
  try {
   selector = Selector.open();
  } catch (IOException e) {
   Log.e("ERROR", "selector open");
  }
  try {
   channel.register(selector, channel.validOps());
  } catch (ClosedChannelException e) {
   Log.e("ERROR", "channel register");
  }

  boolean i = true;

  while(i)
  {
   int readyChannels = 0;
   try {
    readyChannels = selector.select();
   } catch (IOException e) {
    Log.e("ERROR", "selector select");
   }

   if(readyChannels > 0)
   {
    i = false;
   }
  }
    }
}

In Java readyChannels = 1. In Android it is 0. Can anyone help me?


Solution

  • Emulator sits behind a virtual router. You need to configure Network Redirections (port forwarding) to make a certain port on emulator visible to the outside network (including your computer).