Collection deadSockets = null;
Collection processedMessages = null;
for (Iterator it = messages.iterator(); it.hasNext();) {
ChannelMessage message = (ChannelMessage) it.next();
ID id = message.getId();
SocketChannel channel = (SocketChannel) connectedSockets.get(id);
// check if we have a socket for the target of this message
if (channel != null) {
byte[] data = message.getData();
try {
// flush the data directly with regular IO, this method
// saves us the extra work of having to constantly flip and
// clear a ByteBuffer and in a way ensures the message is
// sent in one piece instead of chunks
channel.configureBlocking(true);
channel.socket().getOutputStream().write(data);
channel.socket().getOutputStream().flush();
// turn off blocking
channel.configureBlocking(false);
} catch (IOException e) {
log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
"Error occurred while sending message", e)); //$NON-NLS-1$
if (deadSockets == null) {
deadSockets = new HashSet();
}
deadSockets.add(id);
}
if (processedMessages == null) {
processedMessages = new LinkedList();
}
// store the processed message
processedMessages.add(message);
}
}
// remove all messages that have been processed
if (processedMessages != null) {
messages.removeAll(processedMessages);
}
if (deadSockets != null) {
for (Iterator it = deadSockets.iterator(); it.hasNext();) {
ID id = (ID) it.next();
SocketChannel channel = (SocketChannel) connectedSockets
.remove(id);
Util.closeChannel(channel);
}
}