Search in sources :

Example 1 with BaseNulsData

use of io.nuls.kernel.model.BaseNulsData in project nuls by nuls-io.

the class BroadcastHandler method broadcastToANode.

public BroadcastResult broadcastToANode(BaseMessage message, Node node, boolean asyn) {
    if (!node.isAlive()) {
        return new BroadcastResult(false, NetworkErrorCode.NET_NODE_DEAD);
    }
    if (node.getChannel() == null || !node.getChannel().isActive()) {
        return new BroadcastResult(false, NetworkErrorCode.NET_NODE_MISS_CHANNEL);
    }
    try {
        MessageHeader header = message.getHeader();
        header.setMagicNumber(networkParam.getPacketMagic());
        BaseNulsData body = message.getMsgBody();
        header.setLength(body.size());
        if (asyn) {
            node.getChannel().eventLoop().execute(() -> {
                try {
                    Channel channel = node.getChannel();
                    if (channel != null) {
                        channel.writeAndFlush(Unpooled.wrappedBuffer(message.serialize()));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } else {
            ChannelFuture future = node.getChannel().writeAndFlush(Unpooled.wrappedBuffer(message.serialize()));
            future.await();
            boolean success = future.isSuccess();
            if (!success) {
                return new BroadcastResult(false, NetworkErrorCode.NET_BROADCAST_FAIL);
            }
        }
    } catch (Exception e) {
        Log.error(e);
        return new BroadcastResult(false, NetworkErrorCode.NET_MESSAGE_ERROR);
    }
    return new BroadcastResult(true, KernelErrorCode.SUCCESS);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) BroadcastResult(io.nuls.network.model.BroadcastResult) Channel(io.netty.channel.Channel) MessageHeader(io.nuls.protocol.message.base.MessageHeader) IOException(java.io.IOException) BaseNulsData(io.nuls.kernel.model.BaseNulsData) IOException(java.io.IOException)

Aggregations

Channel (io.netty.channel.Channel)1 ChannelFuture (io.netty.channel.ChannelFuture)1 BaseNulsData (io.nuls.kernel.model.BaseNulsData)1 BroadcastResult (io.nuls.network.model.BroadcastResult)1 MessageHeader (io.nuls.protocol.message.base.MessageHeader)1 IOException (java.io.IOException)1