我再一次遇到了Android中套接字编程的问题。我的问题是Selector.select()返回零,表示没有准备好写入的SocketChannels。同样,同样的代码可以在普通Java中运行,但不能在Android中运行。下面是我的代码:
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;
}
}
}
}在Java中readyChannels = 1,在Android中是0。有谁可以帮我?
发布于 2010-11-03 06:29:49
仿真器位于虚拟路由器后面。您需要配置Network Redirections (端口转发)以使模拟器上的某个端口对外部网络(包括您的计算机)可见。
发布于 2010-11-03 07:22:10
这段NIO代码有几个问题。
https://stackoverflow.com/questions/4081594
复制相似问题