我一直在开发一个与Java联网的程序,该程序使用this tutorial之后的NIO选择器,并且由于某种原因,当我尝试与朋友(在另一个网络中相距较远)测试该程序时,它不起作用
即使当我尝试仅在计算机上自己进行测试时,它也可以正常工作。
以下是该问题的相关代码:
EchoServer类(一个线程):
private Selector selector;
private ServerSocketChannel serverSocket;
private boolean stop = false;
private List<String> pendingStrings;
public EchoServer() throws IOException {
// Get selector
this.selector = Selector.open();
System.out.println("Selector open: " + selector.isOpen());
// Get server socket channel and register with selector
this.serverSocket = ServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("", NetworkingSettings.PORT);
serverSocket.bind(hostAddress);
serverSocket.configur eBlocking(false);
int ops = serverSocket.validOps();
SelectionKey selectKy = serverSocket.register(selector, ops, null);
this.pendingStrings = new ArrayList<>();
}
@Override
public void run() {
while (!stop) {
try {
update();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void update() throws IOException {
System.out.println("Waiting for select...");
int noOfKeys = selector.select();
System.out.println("Number of selected keys: " + noOfKeys);
Set selectedKeys = selector.selectedKeys();
Iterator iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey ky = (SelectionKey) iter.next();
if (ky.isAcceptable()) {
acceptClient();
}
else if (ky.isReadable()) {
readDataFromClient(ky);
}
iter.remove();
}
}
EchoClient类:
private SocketChannel client;
private InetSocketAddress hostAddress;
private boolean connected;
public EchoClient(String ip) {
this.hostAddress = new InetSocketAddress(ip, NetworkingSettings.PORT);
connected = false;
}
public void connect() throws IOException {
if (!connected) {
client = SocketChannel.open(hostAddress);
connected = true;
}
}
public void sendMessage(String message) throws IOException {
try {
byte[] messageBytes = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(messageBytes);
client.write(buffer);
buffer.clear();
} catch (IOException e) {
cleanUp();
}
}
现在,问题似乎出在服务器上,因为当我的朋友运行服务器时(我是客户端),我什至无法连接到服务器。 我怀疑问题的根源是 EchoServer 中的那些行:
InetSocketAddress hostAddress = new InetSocketAddress("", NetworkingSettings.PORT);
serverSocket.bind(hostAddress);
但是我似乎无法弄清楚到底是什么。
重要说明: NetworkingSettings.PORT
是80,我知道它是用于http的端口,也许是问题所在,但我真的想避免使用端口转发和防火墙设置
答案 0 :(得分:0)
问题在于<View style={{flex:1, flexDirection:'column'}}>
<Image .... />
<Text>text here</Text>
</View>
绑定到的InetSocketAddress
。要允许本地主机和远程网络接口上的连接,您需要绑定到通配符地址。这可以通过只使用端口号的ServerSocketChannel
constructor来完成:
InetSocketAddress