All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.prettypb.rpc.server.RpcServerChannel Maven / Gradle / Ivy

There is a newer version: 0.3.5
Show newest version
package net.dongliu.prettypb.rpc.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import net.dongliu.prettypb.rpc.protocol.OobResponse;
import net.dongliu.prettypb.rpc.protocol.RpcError;
import net.dongliu.prettypb.rpc.protocol.RpcResponse;
import net.dongliu.prettypb.rpc.protocol.WirePayload;
import net.dongliu.prettypb.rpc.common.PeerInfo;
import net.dongliu.prettypb.runtime.ProtoBufEncoder;

/**
 * One rpc connection with client
 *
 * @author Dong Liu
 */
public class RpcServerChannel {
    private Channel channel;
    private PeerInfo serverInfo;
    private PeerInfo clientInfo;
    private boolean compress;

    public RpcServerChannel(Channel channel, PeerInfo serverInfo, PeerInfo clientInfo,
                            boolean compress) {
        this.channel = channel;
        this.serverInfo = serverInfo;
        this.clientInfo = clientInfo;
        this.compress = compress;
    }

    /**
     * channel unique name used to identify
     *
     * @return
     */
    public String getChannelName() {
        return clientInfo.getName();
    }

    public PeerInfo getServerInfo() {
        return serverInfo;
    }

    public Channel getChannel() {
        return channel;
    }

    public PeerInfo getClientInfo() {
        return clientInfo;
    }

    public boolean isCompress() {
        return compress;
    }

    /**
     * send response
     */
    public void sendRpcResponse(int correlationId, Object response, Class clazz) {
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setCorrelationId(correlationId);
        rpcResponse.setResponseBytes(ProtoBufEncoder.toBytes(response, clazz));
        WirePayload wirePayload = new WirePayload();
        wirePayload.setRpcResponse(rpcResponse);
        channel.writeAndFlush(wirePayload);
    }

    public ChannelFuture sendOobResponse(int correlationId, byte[] bytes) {
        OobResponse oobResponse = new OobResponse();
        oobResponse.setCorrelationId(correlationId);
        oobResponse.setMessageBytes(bytes);
        WirePayload wirePayload = new WirePayload();
        wirePayload.setOobResponse(oobResponse);
        return channel.writeAndFlush(wirePayload);
    }

    /**
     * send error response
     */
    public void sendRpcError(int correlationId, String msg) {
        RpcError rpcError = new RpcError();
        rpcError.setCorrelationId(correlationId);
        rpcError.setErrorMessage(msg);
        WirePayload wirePayload = new WirePayload();
        wirePayload.setRpcError(rpcError);
        channel.writeAndFlush(wirePayload);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy