我正在使用 java.nio 包在两个 android 设备之间创建 TCP 客户端-服务器连接。这是客户端的操作:
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress(gameAddr, 8001));
这是服务器的作用:
try
{
tokenizer = new FixedSeparatorMessageTokenizer(Strings.DELIMITER, Charset.forName("UTF-8"));
selector = SelectorProvider.provider().openSelector();
sChan = ServerSocketChannel.open();
InetSocketAddress iaddr = new InetSocketAddress(InetAddress.getLocalHost(), 8001);
sChan.configureBlocking(false);
sChan.socket().bind(iaddr);
sChan.register(selector, SelectionKey.OP_ACCEPT);
sockets = new Vector<SocketChannel>();
}
catch (Exception e)
{
e.printStackTrace();
}
Iterator<SelectionKey> it;
try {
while (selector.isOpen())
{
selector.select();
it = selector.selectedKeys().iterator();
while (it.hasNext())
{
SelectionKey key = it.next();
it.remove();
if (!key.isValid())
{
continue;
}
if (key.isConnectable())
{
SocketChannel ssc = (SocketChannel) key.channel();
if (ssc.isConnectionPending()) ssc.finishConnect();
}
if (key.isAcceptable())
{
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel newClient = ssc.accept();
newClient.configureBlocking(false);
newClient.register(selector, SelectionKey.OP_READ);
sockets.add(newClient);
System.out.println("Connection from " + newClient.socket().getInetAddress().getHostAddress());
}
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer data = ByteBuffer.allocate(sc.socket().getSendBufferSize());
System.out.println("Data from " + sc.socket().getInetAddress().getHostAddress());
if (sc.read(data) == -1) //is this a socket close?
{
continue;
}
data.flip();
tokenizer.addBytes(data);
while(tokenizer.hasMessage())
{
ParsedMessage pm = new ParsedMessage(tokenizer.nextMessage());
pm.setAttachment(sc);
synchronized(Q) { Q.add(pm); }
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
它们都使用相同的端口 8001(我尝试了不同的端口)并且它们在同一个 LAN 中,因为 UDP 数据包实际上是从一个设备到另一个设备。可能是什么问题?