zoukankan      html  css  js  c++  java
  • WCF websocket

    WebSocket, like as TCP, is a bi-directional, full-duplex communication channel over a single TCP connection but it shortens abundant complications close to bi-directional communication as well as connection management which we typically comprehend while using TCP. WebSocket channels start as normal HTTP channels which are then upgraded to WebSocket channels by using handshaking, allowing cooperative TCP communication between client and server.

    WCF hosts provision for WebSockets over the standard HTTP ports 80 and 443. The standard HTTP port allows WebSockets to communicate across the web through mediators. WCF introduces two standard bindings to support communication over a WebSocket transport.

    • NetHttpBinding
    • NetHttpsBinding 

    These bindings are designed for consuming WebSocket services and will perceive whether they are used with a request-reply contract or duplex contract and change their behavior according to it. They will use HTTP/HTTPS for request-reply contracts and WebSockets for duplex contracts. We can override this behavior by using WebSocketTransportUsage setting:

    • Always – Enforce to use WebSockets
    • Never – Stops to use WebSockets
    • WhenDuplex – This is the default value.

    Define Callback Contract 

    public interface INotificationServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnNotificationSend(Notification notification);
    }
    

    Clients will implement this contract through which the service can send messages back to the clients. To have a better understanding how duplex channel works, I would recommend you to have a look at this link.

    Define Service Contract  

    [ServiceContract(CallbackContract = typeof(INotificationServiceCallback))]
    public interface INotificationService
    {
        [OperationContract]
        void SendNotification(Notification notification);
    
        [OperationContract]
        void SubscribeForNotification
        (List<NotificationType> notificationTypes);
    
        [OperationContract]
        void UnsubscribeForNotification
        (List<NotificationType> notificationTypes);
    }
    

    Here, INotificationServiceCallback has been specified as the callback contract.

    Implement Service Contract 

    public class NotificationServiceService : INotificationService
    {
        private INotificationServiceCallback Subscriber
        {
            get { return OperationContext.Current.
            GetCallbackChannel<INotificationServiceCallback>();  }
        }
    
        public void SendNotification(Notification notification)
        {
            NotificationManager.Instance.SendNotification(notification, Subscriber);
        }
    
        public void SubscribeForNotification
        (List<NotificationType> notificationTypes)
        {
            NotificationManager.Instance.AddSubscriber(Subscriber, notificationTypes);
        }
    
        public void UnsubscribeForNotification
        (List<NotificationType> notificationTypes)
        {
            NotificationManager.Instance.RemoveSubscriber(Subscriber, notificationTypes);
        }
    }
    

    In the implementation, we retain the callback channel using the OperationContext which has been passed to the NotificationManager and finally NotificationManager does the rest of the Jobs.

    Implement Notification Manager  

    public class NotificationManager
    {
        private volatile static NotificationManager _notificationManager = null;
        private static readonly object SyncLock = new object();
        private NotificationManager()
        {
            Subscribers = new Dictionary
            <INotificationServiceCallback, List<NotificationType>>();
            Notifications = new List<Notification>();
        }
    
        public Dictionary<INotificationServiceCallback,
        List<NotificationType>> Subscribers { get; private set; }
        public List<Notification> Notifications { get; private set; }
        public static NotificationManager Instance
        {
            get
            {
                lock (SyncLock)
                {
                    if (_notificationManager == null)
                    {
                        lock (SyncLock)
                        {
                            _notificationManager = new NotificationManager();
                        }
                    }
                }
                return _notificationManager;
            }
        }
    
        public void AddSubscriber(INotificationServiceCallback subscriber,
        List<NotificationType> notificationType)
        {
            if (!Subscribers.ContainsKey(subscriber))
                Subscribers.Add(subscriber, notificationType);
            else
            {
                var newNotificationType = notificationType.Where
                (n => Subscribers[subscriber].Any(n1 => n1 != n));
                Subscribers[subscriber].AddRange(newNotificationType);
            }
        }
    
        public void RemoveSubscriber(INotificationServiceCallback
        subscriber, List<NotificationType> notificationTypes)
        {
            if (Subscribers.ContainsKey(subscriber))
            {
                notificationTypes.ForEach(notificationType =>
                Subscribers[subscriber].Remove(notificationType));
    
                if (Subscribers[subscriber].Count < 1)
                    Subscribers.Remove(subscriber);
            }
        }
    
        public void AddNotification(Notification notification)
        {
            if (!Notifications.Contains(notification))
                Notifications.Add(notification);
        }
    
        public void RemoveNotification(Notification notification)
        {
            if (Notifications.Contains(notification))
                Notifications.Remove(notification);
    
        }
    
        public void SendNotification
        (Notification notification, INotificationServiceCallback sender)
        {
            foreach (var existingSubscriber in Subscribers)
            {
                if (existingSubscriber.Value.Any(n =>
                n == notification.NotificationType) &&
                existingSubscriber.Key != sender)
                {
                    if (((ICommunicationObject)existingSubscriber.Key).
                    State == CommunicationState.Opened)
                    {
                        existingSubscriber.Key.OnNotificationSend(notification);
                    }
                }
            }
        }
    }
    

    As we see, NotificationManager maintains a dictionary to hold the client list that have been subscribed for getting the notifications for different notification types. If any client broadcast messages with Notification types, the subscribers who only subscribe to get the notification for these notification types will get these messages. The code is itself self-explanatory. If you go through the code portion, you will easily have an idea about that.

    Service Configuration 

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.web>
         <compilation debug="true" targetFramework="4.5" />
         <httpRuntime targetFramework="4.5" />
      </system.web>
       <system.serviceModel>
            <protocolMapping>
              <add scheme="http" binding="netHttpBinding" />
            </protocolMapping>
            <behaviors>
                <serviceBehaviors>
                    <behavior name="">
                        <serviceMetadata httpGetEnabled="true" 
                        httpsGetEnabled="true" />
                        <serviceDebug includeExceptionDetailInFaults=
                        "false" />
                    </behavior>
                </serviceBehaviors>
            </behaviors>
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
            multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
        <system.webServer>
            <directoryBrowse enabled="true" />
        </system.webServer>
    </configuration>

    NetHttpBinding has been used for the default endpoints. If you want to acquaint yourself a bit more about the configuration updates, I would suggest having a look at that.

    Okay Service Portion has been done. Now, let's move at the client portions,

    Implement Callback Contract and Define Client  

    class Program : INotificationServiceCallback
    {
        private NotificationServiceClient _notificationServiceClient;
        private InstanceContext _instanceContext;
        private readonly List<NotificationType>
        _notificationTypes = Enum.GetValues(typeof(NotificationType)).
        Cast<NotificationType>().ToList();
    
        public NotificationServiceClient NotificationServiceClient
        {
            get
            {
                return _notificationServiceClient ??
                       (_notificationServiceClient =
                       new NotificationServiceClient(CallbackInstance,
                       "netHttpBinding_INotificationService"));
            }
        }
    
        public InstanceContext CallbackInstance
        {
            get { return _instanceContext ??
            (_instanceContext = new InstanceContext(this)); }
        }
    
        static void Main(string[] args)
        {
            var objProgram = new Program();
            Console.WriteLine("Write exit to shut down....
    ");
            Console.WriteLine("Wait...Subscribing for notifications
    ");
            objProgram.SubscribeForNotification();
            Console.WriteLine("Subscription done...
            Now you can send notifacation
    ");
            var readMsg = Console.ReadLine();
    
            while (readMsg.ToString(CultureInfo.InvariantCulture).
            ToLower().Equals("exit") == false)
            {
                objProgram.SendNotification(readMsg);
                Console.WriteLine("Notification has been send......
    ");
                readMsg = Console.ReadLine();
            }
            objProgram.UnsubscribeForNotification();
        }
    
        public void OnNotificationSend(Notification notification)
        {
            Console.WriteLine(string.Format("New Notification Received
            n
    Message :{0}
    Time :{1}
    
    ", notification.
            NotificationMsg, notification.PostingTime));
        }
    
        private void SubscribeForNotification()
        {
            NotificationServiceClient.SubscribeForNotification(_notificationTypes);
        }
    
        private void UnsubscribeForNotification()
        {
            NotificationServiceClient.UnsubscribeForNotification(_notificationTypes);
        }
    
        private void SendNotification(string msg)
        {
            NotificationServiceClient.SendNotification(new Notification()
            {
                NotificationMsg = msg,
                PostingTime = DateTime.Now
            });
        }
    }
    

    The client application has a property of InstanceContext and NotificationServiceClient, also it specifies the implementation of the INotificationServiceCallback interface. When a client subscribes for the notifications to the service, the service will send the notifications to the client using the callback contract specified.

    Implement Service Client 

        public class NotificationServiceClient : 
    DuplexClientBase<INotificationService>, INotificationService
        {
            public NotificationServiceClient(InstanceContext callbackInstance) :
                base(callbackInstance)
            {
            }
    
            public NotificationServiceClient(InstanceContext 
            callbackInstance, string endpointConfigurationName) :
                base(callbackInstance, endpointConfigurationName)
            {
            }
    
            public void SendNotification(Notification notification)
            {
                Channel.SendNotification(notification);
            }
    
            public void SubscribeForNotification
            (List<NotificationType> notificationTypes)
            {
                Channel.SubscribeForNotification(notificationTypes);
            }
    
            public void UnsubscribeForNotification
            (List<NotificationType> notificationTypes)
            {
                Channel.UnsubscribeForNotification(notificationTypes);
            }
        }

    Client Configuration 

    <?xml version="1.0"?>
    <configuration>
      <system.serviceModel>
        <bindings>
          <netHttpBinding>
            <binding name="NetHttpBinding_INotificationService">
              <webSocketSettings transportUsage="Always" />
            </binding>
          </netHttpBinding>
        </bindings>
        <client>
          <endpoint address="ws://localhost/websocket/NotificationService.svc"
              binding="netHttpBinding"
              contract="Rashim.RND.WCF.WebSockect.Interfaces.INotificationService"
                 bindingConfiguration="NetHttpBinding_INotificationService"
              name="netHttpBinding_INotificationService">
            <identity>
              <dns value="localhost" />
            </identity>
          </endpoint>
        </client>
      </system.serviceModel>
    </configuration>

    This is as usual and not anything special, what you need to do in the client configuration is to specify the client side endpoint using the NetHttpBinding.

    Finally DataContracts

    [DataContract]
    public class Notification
    {
        [DataMember]
        public string NotificationMsg { get; set; }
        [DataMember]
        public DateTime PostingTime { get; set; }
        [DataMember]
        public NotificationType NotificationType { get; set; }
    }
    
    [DataContract]
    public enum NotificationType
    {
        [EnumMember]
        General,
        [EnumMember]
        Greetings
    }
    

    Using the Source Code 

    You need to host the Rashim.RND.WCF.WebSockect.Services in IIS8 and then put the appropriate endpoint address to the client configuration file. After completing the Service hosting, you need to run the two instances of Rashim.RND.WCF.WebSockect.Clients, then you can send message from instance to another one just like the given figure below:

    References 

    原文:http://www.codeproject.com/Articles/613677/WebSocket-in-WCF

    继承DuplexClientBase类,初始化时关联WCF,并进行业务扩展。

    WCF提供相关的数据服务和回调接口,通过OperationContext.Current.GetCallbackChannel获取通道对象,调用回调方法。

  • 相关阅读:
    (四)自定义多个Realm以及Authenticator与AuthenticationStrategy
    (三)自定义Realm
    (二)shiro之jsp标签
    (一)shiro简介和用户登录demo及角色管理
    解决Cannot change version of project facet Dynamic web module to 2.5(转)
    (十二)easyUI之表单和验证完成登录页面
    (十一)springmvc和spring的整合
    (十)springmvc之文件的处理
    (九)springmvc之json的数据请求(客户端发送json数据到服务端)
    (九)springmvc之json的处理(服务端发送json数据到客户端)
  • 原文地址:https://www.cnblogs.com/zorro8z8/p/5526091.html
Copyright © 2011-2022 走看看