gpt4 book ai didi

java - SocketChannel 还没有准备好

转载 作者:行者123 更新时间:2023-11-29 22:30:54 25 4
gpt4 key购买 nike

我再次遇到 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。谁能帮帮我?

最佳答案

模拟器位于虚拟路由器后面。你需要配置 Network Redirections (端口转发)使模拟器上的某个端口对外部网络(包括您的计算机)可见。

关于java - SocketChannel 还没有准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4081594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com