首页 > 解决方案 > WCF接口服务契约实例直接调用函数

问题描述

我有一个类(名为 Sender),它有一个定义 WCF 服务合同的 Icommunicator 接口成员。

public class Sender
{
    private ICommunicator channel;
    private ChannelFactory<ICommunicator> factory = null;

在同一个 .cs 文件中,有一个class Receiver继承自 Icommunicator 的文件。

定义服务契约的接口如下:

[ServiceContract(Namespace = "P2PComm")]
public interface ICommunicator
{
    [OperationContract(IsOneWay = true)]
    void PostMessage(CommMessage msg);

    // used only locally so not exposed as a service method
    CommMessage GetMessage();

    [OperationContract]
    bool openFileForWrite(string fileName);
    [OperationContract]
    bool writeFileBlock(byte[] block);
    [OperationContract]
    void closeFile();
}

Sender类内部有一个连接函数,它Icommunicator channel直接使用该成员来调用该PostMessage函数。

    // attempts to connect to Receiver instance
    // attempts a finite number of times to connect to a Receiver
    // first attempt to send will throw exception of no listener
    // at the specified endpoint
    // to test that we attempts to send a connect message
    public bool connect(string toAddress)
    {
        int timeToSleep = 500;
        CreateSendChannel(toAddress);
        CommMessage connectMsg = new CommMessage(CommMessage.MessageType.connect);
        connectMsg.to = toAddress;
        connectMsg.from = fromAddress;
        connectMsg.command = Msg.Command.connect;
        

        while (true)
        {
            try
            {
                channel.PostMessage(connectMsg);
                tryCount = 0;
                lastUrl = toAddress;
                return true;
            }
            catch (Exception ex)
            {
                if (++tryCount < maxCount)
                {
                    Thread.Sleep(timeToSleep);
                }
                else
                {
                    lastError = ex.Message;
                    lastUrl = "";
                    tryCount = 0;
                    return false;
                }

            }
        }
    }

我不明白这里发生了什么我不是从Icommunicator接口继承的,而是我用它来调用它的一个函数,那么在这种情况下调用哪个函数?

当我用调试器运行它时,它没有进入函数,但它仍然能够发送消息。

标签: c#wcf

解决方案


推荐阅读