Search in sources :

Example 1 with ConnectionInfo

use of org.bcos.channel.handler.ConnectionInfo in project web3sdk by FISCO-BCOS.

the class Service method asyncSendChannelMessage.

public void asyncSendChannelMessage(ChannelRequest request, ChannelResponseCallback callback) {
    try {
        logger.debug("处理链上链下请求: " + request.getMessageID());
        callback.setService(this);
        ChannelMessage channelMessage = new ChannelMessage();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        // 链上链下请求0x20
        channelMessage.setType((short) 0x20);
        channelMessage.setData(request.getContent().getBytes());
        try {
            List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
            List<ConnectionInfo> toConnectionInfos = new ArrayList<ConnectionInfo>();
            // 设置发送节点
            ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
            if (fromChannelConnections == null) {
                // 没有找到对应的链
                // 返回错误
                logger.error("没有找到本机构:{}", request.getFromOrg());
                throw new Exception("未找到本机构");
            }
            fromConnectionInfos.addAll(fromChannelConnections.getConnections());
            logger.debug("发送结构:{} 节点数:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            callback.setFromChannelConnections(fromChannelConnections);
            callback.setFromConnectionInfos(fromConnectionInfos);
            // 设置目的节点
            ChannelConnections toChannelConnections = allChannelConnections.get(request.getToOrg());
            if (toChannelConnections == null) {
                logger.error("未找到目的机构: {}", request.getToOrg());
                throw new Exception("未找到目标机构");
            }
            toConnectionInfos.addAll(toChannelConnections.getConnections());
            logger.debug("机构:{} 节点数:{}", request.getToOrg(), toChannelConnections.getConnections().size());
            callback.setToConnectionInfos(toConnectionInfos);
            // 设置消息内容
            callback.setRequest(channelMessage);
            seq2Callback.put(request.getMessageID(), callback);
            if (request.getTimeout() > 0) {
                final ChannelResponseCallback callbackInner = callback;
                callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                    ChannelResponseCallback _callback = callbackInner;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        // 处理超时逻辑
                        _callback.onTimeout();
                    }
                }, request.getTimeout(), TimeUnit.MILLISECONDS));
            }
            callback.retrySendMessage(0);
        } catch (Exception e) {
            logger.error("发送消息异常 消息未发出", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(100);
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            callback.onResponse(response);
            return;
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : ChannelConnections(org.bcos.channel.handler.ChannelConnections) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ArrayList(java.util.ArrayList) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.bcos.channel.dto.ChannelResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChannelMessage(org.bcos.channel.dto.ChannelMessage)

Example 2 with ConnectionInfo

use of org.bcos.channel.handler.ConnectionInfo in project web3sdk by FISCO-BCOS.

the class Server method onLocalMessage.

public void onLocalMessage(ChannelHandlerContext ctx, Message message) {
    try {
        logger.debug("处理来自SDK请求: " + message.getSeq());
        ChannelHandlerContext remoteCtx = null;
        ConnectionPair pair = seq2Connections.get(message.getSeq());
        if (pair != null) {
            // 已有这个seq,发往远端的响应
            logger.debug("已有seq");
            // 发送到远端的响应
            remoteCtx = pair.remoteConnection;
            if (message.getType() != 0x31) {
                pair.localConnection = ctx;
            }
            ByteBuf out = remoteCtx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);
            logger.debug("消息发送至:{}:{}", ((SocketChannel) remoteCtx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort());
            remoteCtx.writeAndFlush(out);
        } else {
            pair = new ConnectionPair();
            pair.localConnection = ctx;
            pair.setServer(this);
            pair.setMessage(message);
            // 本地发往远程的消息,如果是链上链下,需要按给定的nodeID发
            if (message.getType() == 0x20 || message.getType() == 0x21) {
                // 获取nodeID
                logger.debug("链上链下消息一期 指定目的地");
                if (message.getData().length < 256) {
                    logger.error("错误的channel消息 长度不足256:{}", message.getData().length);
                }
                // 获取nodeID对应的连接,检查可用性
                String nodeID = new String(message.getData(), 128, 128);
                logger.debug("转发至:{}", nodeID, message.getData());
                for (ConnectionInfo conn : remoteConnections.getConnections()) {
                    if (conn.getNodeID().equals(nodeID)) {
                        remoteCtx = remoteConnections.getNetworkConnectionByHost(conn.getHost(), conn.getPort());
                        pair.remoteConnection = remoteCtx;
                        break;
                    }
                }
                if (remoteCtx == null || !remoteCtx.channel().isActive()) {
                    // 找不到连接,错误
                    logger.error("发送连接异常,返回错误99");
                    if (message.getType() == 0x20 || message.getType() == 0x21) {
                        message.setType((short) 0x21);
                    } else {
                        message.setType((short) 0x31);
                    }
                    message.setResult(99);
                    ByteBuf out = ctx.alloc().buffer();
                    message.writeHeader(out);
                    message.writeExtra(out);
                    ctx.writeAndFlush(out);
                    return;
                }
                ByteBuf out = remoteCtx.alloc().buffer();
                message.writeHeader(out);
                message.writeExtra(out);
                logger.debug("消息发送至:{}:{}", ((SocketChannel) remoteCtx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort());
                remoteCtx.writeAndFlush(out);
                pair.init();
            } else {
                logger.debug("其它消息,使用ConnectionPair逻辑");
                pair.setRemoteChannelConnections(remoteConnections);
                List<ConnectionInfo> remoteConnectionInfos = new ArrayList<ConnectionInfo>();
                remoteConnectionInfos.addAll(remoteConnections.getConnections());
                pair.setRemoteConnectionInfos(remoteConnectionInfos);
                seq2Connections.put(message.getSeq(), pair);
                pair.init();
                pair.retrySendRemoteMessage();
            }
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ByteBuf(io.netty.buffer.ByteBuf) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with ConnectionInfo

use of org.bcos.channel.handler.ConnectionInfo in project web3sdk by FISCO-BCOS.

the class Service method asyncSendChannelMessage2.

public void asyncSendChannelMessage2(ChannelRequest request, ChannelResponseCallback2 callback) {
    try {
        logger.debug("处理链上链下请求: " + request.getMessageID());
        callback.setService(this);
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        // 链上链下请求0x30
        channelMessage.setType((short) 0x30);
        channelMessage.setData(request.getContent().getBytes());
        channelMessage.setTopic(request.getToTopic());
        try {
            List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
            // 设置发送节点
            ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
            if (fromChannelConnections == null) {
                // 没有找到对应的链
                // 返回错误
                logger.error("没有找到本机构:{}", orgID);
                throw new Exception("未找到本机构");
            }
            fromConnectionInfos.addAll(fromChannelConnections.getConnections());
            logger.debug("发送机构:{} 节点数:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            callback.setFromChannelConnections(fromChannelConnections);
            callback.setFromConnectionInfos(fromConnectionInfos);
            // 设置消息内容
            callback.setRequest(channelMessage);
            seq2Callback.put(request.getMessageID(), callback);
            if (request.getTimeout() > 0) {
                final ChannelResponseCallback2 callbackInner = callback;
                callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                    ChannelResponseCallback2 _callback = callbackInner;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        // 处理超时逻辑
                        _callback.onTimeout();
                    }
                }, request.getTimeout(), TimeUnit.MILLISECONDS));
            }
            callback.retrySendMessage();
        } catch (Exception e) {
            logger.error("发送消息异常 消息未发出", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(100);
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            callback.onResponse(response);
            return;
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : ChannelConnections(org.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.bcos.channel.dto.ChannelMessage2) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ArrayList(java.util.ArrayList) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.bcos.channel.dto.ChannelResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 4 with ConnectionInfo

use of org.bcos.channel.handler.ConnectionInfo in project web3sdk by FISCO-BCOS.

the class Server method onTopic.

public void onTopic(ChannelHandlerContext ctx, Message message) {
    logger.debug("来自SDK的topics消息: {} {}", message.getSeq(), new String(message.getData()));
    String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
    // 
    Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
    ConnectionInfo info = localConnections.getConnectionInfo(host, port);
    if (info != null) {
        try {
            List<String> topics = objectMapper.readValue(message.getData(), List.class);
            info.setTopics(topics);
            broadcastTopic();
        } catch (Exception e) {
            logger.error("解析topic错误", e);
        }
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with ConnectionInfo

use of org.bcos.channel.handler.ConnectionInfo in project web3sdk by FISCO-BCOS.

the class Server method broadcastTopic.

public void broadcastTopic(ChannelHandlerContext ctx) {
    try {
        Message message = new Message();
        message.setResult(0);
        // topic设置topic消息0x32
        message.setType((short) 0x32);
        message.setSeq(UUID.randomUUID().toString().replaceAll("-", ""));
        // 综合所有的topics
        Set<String> allTopics = new HashSet<String>();
        for (ConnectionInfo connectionInfo : localConnections.getConnections()) {
            // 有效的连接,才增加到全局topic
            ChannelHandlerContext localCtx = localConnections.getNetworkConnectionByHost(connectionInfo.getHost(), connectionInfo.getPort());
            if (localCtx != null && localCtx.channel().isActive()) {
                logger.debug("节点:{}:{} 关注topics: {}", connectionInfo.getHost(), connectionInfo.getPort(), connectionInfo.getTopics());
                allTopics.addAll(connectionInfo.getTopics());
            }
        }
        message.setData(objectMapper.writeValueAsBytes(allTopics.toArray()));
        logger.debug("全部topics: {}", new String(message.getData()));
        if (ctx == null) {
            // 广播到所有远端节点
            for (String key : remoteConnections.getNetworkConnections().keySet()) {
                ChannelHandlerContext remoteCtx = remoteConnections.getNetworkConnections().get(key);
                if (remoteCtx != null && remoteCtx.channel().isActive()) {
                    ByteBuf out = remoteCtx.alloc().buffer();
                    message.writeHeader(out);
                    message.writeExtra(out);
                    if (remoteCtx != null && remoteCtx.channel().isActive()) {
                        logger.debug("topic广播至 {}:{}", ((SocketChannel) remoteCtx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort());
                        remoteCtx.writeAndFlush(out);
                    }
                }
            }
        } else {
            // 发送到指定远端节点
            logger.debug("topic发送至 {}:{}", ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) ctx.channel()).remoteAddress().getPort());
            ByteBuf out = ctx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);
            ctx.writeAndFlush(out);
        }
    } catch (Exception e) {
        logger.error("错误", e);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) Message(org.bcos.channel.handler.Message) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ByteBuf(io.netty.buffer.ByteBuf) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HashSet(java.util.HashSet)

Aggregations

UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 ConnectionInfo (org.bcos.channel.handler.ConnectionInfo)6 SocketChannel (io.netty.channel.socket.SocketChannel)4 ByteBuf (io.netty.buffer.ByteBuf)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 ArrayList (java.util.ArrayList)3 Timeout (io.netty.util.Timeout)2 TimerTask (io.netty.util.TimerTask)2 HashSet (java.util.HashSet)2 ChannelResponse (org.bcos.channel.dto.ChannelResponse)2 ChannelConnections (org.bcos.channel.handler.ChannelConnections)2 Random (java.util.Random)1 ChannelMessage (org.bcos.channel.dto.ChannelMessage)1 ChannelMessage2 (org.bcos.channel.dto.ChannelMessage2)1 Message (org.bcos.channel.handler.Message)1