Azure

时间:2017-06-26 12:34:27

标签: c# json wcf azure

我有一个azure云服务项目,它托管了一些服务(myService.svc,通过&#34添加新服务引用"从wsdl文件生成;)。

效果很好,操作起来非常简单。

服务声明示例:

<service behaviorConfiguration="myBehaviour" name="myService">
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <endpoint address="" behaviorConfiguration="" binding="wsHttpBinding" bindingConfiguration="CentralSystemServiceSoap" contract="CentralSystemService" />
      </service>

[System.ServiceModel.ServiceContractAttribute("CentralSystemService")]
public interface CentralSystemService
{

}

但我的一些设备现在需要使用JSON的websockets协议。

我已经阅读了很多关于websockets如何工作的内容,而且我发现了许多不同的实现,这些实现似乎过于复杂,但主要是它们都完全不同。我已经寻找了更接近WCF服务的实现。但是所有的例子都没有包括握手部分。例如。

我的项目是在azure(云服务实例)上发布的,我以前的所有svc都必须继续工作。

我可以将所有内容保存在同一个项目中并创建我的websockets JSON服务吗? 我问这个问题是因为我发现的大多数例子都包含一个Main函数来打开服务器的监听器,而且我还没能在我的Cloud项目中设置启动主方法。

您会向我推荐哪种实施方式?

谢谢,

1 个答案:

答案 0 :(得分:1)

使用NetHttpBinding绑定时,我们可以通过回调契约在WebSockets上在WCF服务和客户端之间进行通信。以下步骤供您参考。

步骤1,在web.config中,我们需要将NetHttpBinding配置为protocolMapping。

<protocolMapping>
  <add scheme="http" binding="netHttpBinding"/>
  <add scheme="https" binding="netHttpsBinding"/>
</protocolMapping>

步骤2,使用回调创建服务合同。

[ServiceContract]
public interface IServiceCallback
{
    [OperationContract(IsOneWay = true)]
    Task SendMessageBack(string message);
}

[ServiceContract(CallbackContract = typeof(IServiceCallback))]
public interface IService
{
    [OperationContract(IsOneWay = true)]
    Task DoSomething(string parameter);
}

步骤3,在WCF服务中,我们可以获取服务回调的实例并使用它向客户端发送消息。

public class MySocketService : IService
{
    public async Task DoSomething(string parameter)
    {
        var callback = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
        var random = new Random();
        int randomNumber = 2;

        while (((IChannel)callback).State == CommunicationState.Opened)
        {
            await callback.SendMessageBack("Call back message:" + randomNumber);
            randomNumber += random.Next(10);
            await Task.Delay(1000);
        }
    }
}

步骤4,在客户端,我们需要实现服务回调接口并使用它来接收来自服务的消息。

class Program
{
    static void Main(string[] args)
    {
        var context = new InstanceContext(new CallbackHandler());
        var client = new ServiceClient(context);
        client.DoSomething("a message");
        Console.ReadLine();
    }
}


public class CallbackHandler : IServiceCallback
{
    void IServiceCallback.SendMessageBack(string message)
    {
        Console.WriteLine(message);
    }
}

enter image description here

有关详细信息,请参阅以下链接供您参考。

How to: Create a WCF Service that Communicates over WebSockets