Я пытался использовать SocketChannel
для своего приложения для Android. но проблема, с которой я столкнулся, заключается в том, что я не могу прочитать ответ, даже если я успешно написал SocketChannel
. Кроме того, я получаю selKey.isWritable()
, selKey.isReadable()
и selKey.isConnectable()
одновременно, как мне поступить в таком случае?
Пожалуйста, помогите мне понять, где я ошибаюсь?
SocketChannel socketChannel = null;
try {
// Create client SocketChannel
socketChannel = SocketChannel.open();
// nonblocking I/O
socketChannel.configureBlocking(false);
// Connection to host port 8000
socketChannel.connect(new InetSocketAddress(pTargetURL,pTargetPort));
// Create selector
Selector selector = Selector.open();
// Record to selector (OP_CONNECT type)
socketChannel.register(selector, SelectionKey.OP_CONNECT);
// Wait for events
while (true) {
selector.select();
// Get list of selection keys with pending events
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
// Process each key at a time
while (iterator.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey)iterator.next();
// Remove it from the list to indicate that it is being processed
iterator.remove();
if (selKey.isValid() && selKey.isConnectable()) {
// Get channel with connection request
SocketChannel sChannel = (SocketChannel)selKey.channel();
boolean success = sChannel.finishConnect();
if (success) {
socketChannel.register(selector, SelectionKey.OP_WRITE);
}
else {
// An error occurred; handle it
// Unregister the channel with this selector
selKey.cancel();
}
}
else if(selKey.isValid() && selKey.isWritable()) {
SocketChannel sChannel = (SocketChannel)selKey.channel();
// See Writing to a SocketChannel
ByteBuffer requestBuffer = null;
String requestHeader = pRequestMethod + " /" + pTargetFile + " HTTP/1.1" + "\r\n";
String requestHost = "Host: " + pTargetURL + "\r\n";
String requestlength = "Content-Length: " + pRequestXML.length() + "\r\n\r\n";
String requestXML = pRequestXML + "\r\n";
String finalRequest = requestHeader + requestHost + requestlength + requestXML;
requestBuffer = ByteBuffer.wrap(finalRequest.getBytes(Charset.forName("UTF-8")));
sChannel.write(requestBuffer);
socketChannel.register(selector, SelectionKey.OP_READ);
}
else if (selKey.isValid() && selKey.isReadable()) {
// Get channel with bytes to read
SocketChannel sChannel = (SocketChannel)selKey.channel();
// See Reading from a SocketChannel
ByteBuffer responseBuffer = ByteBuffer.allocate(1024);
String responseString = null;
while(sChannel.read(responseBuffer) > 0) {
responseString = new String(responseBuffer.array(), Charset.forName("UTF-8"));
}
}
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try {
socketChannel.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
finishConnect()
возвращает false, то делать вывод, что произошла ошибка, неправильно: нет причин отменять ключ. Вы также не проверяете EOS при чтении или ">обработка записи нулевой длины при записи. - person user207421   schedule 21.10.2014