/** * Closes the connection to the peer if one exists, or immediately closes the connection as soon * as it opens */ public void close() { lock.lock(); try { if (writeTarget == null) { closePending = true; return; } } finally { lock.unlock(); } writeTarget.closeConnection(); }
/** * Sets the {@link MessageWriteTarget} used to write messages to the peer. This should almost * never be called, it is called automatically by {@link org.bitcoinj.net.NioClient} or {@link * org.bitcoinj.net.NioClientManager} once the socket finishes initialization. */ @Override public void setWriteTarget(MessageWriteTarget writeTarget) { checkArgument(writeTarget != null); lock.lock(); boolean closeNow = false; try { checkArgument(this.writeTarget == null); closeNow = closePending; this.writeTarget = writeTarget; } finally { lock.unlock(); } if (closeNow) writeTarget.closeConnection(); }
/** * Sends the given message to the peer. Due to the asynchronousness of network programming, there * is no guarantee the peer will have received it. Throws NotYetConnectedException if we are not * yet connected to the remote peer. TODO: Maybe use something other than the unchecked * NotYetConnectedException here */ public void sendMessage(Message message) throws NotYetConnectedException { lock.lock(); try { if (writeTarget == null) throw new NotYetConnectedException(); } finally { lock.unlock(); } // TODO: Some round-tripping could be avoided here ByteArrayOutputStream out = new ByteArrayOutputStream(); try { serializer.serialize(message, out); writeTarget.writeBytes(out.toByteArray()); } catch (IOException e) { exceptionCaught(e); } }