コード例 #1
0
ファイル: WorkerRole.cs プロジェクト: marisks/NewsSite
        public override void Run()
        {
            Trace.WriteLine("Starting processing of messages");

            InClient.OnMessage((receivedMessage) =>
            {
                try
                {
                    Trace.WriteLine("Processing Service Bus message: " +
                                    receivedMessage.SequenceNumber.ToString());

                    var importFile = receivedMessage.GetBody <ImportFile>();
                    var container  = CreateStorageContainer();
                    var blob       = container.GetBlockBlobReference(importFile.Name);

                    var articles = ReadArticles(blob).ToList();

                    articles.ForEach(article =>
                    {
                        var message = new BrokeredMessage(article);
                        OutClient.Send(message);
                    });

                    receivedMessage.Complete();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception: {0} \n Stack Trace: {1}",
                                     ex.Message, ex.StackTrace);
                }
            });

            CompletedEvent.WaitOne();
        }
コード例 #2
0
        /// <summary>
        /// <para>An endpoint's parameters:</para>
        /// <para>1: Endpoint that starts with "/" like /example</para>
        /// <para>2: OnConnected callback with endpoint with / at the beginning, unique connection ID and send message action. Send message action should not be called in OnConnected call.</para>
        /// <para>3: OnMessage callback with endpoint with / at the beginning, unique connection ID, message and send message action</para>
        /// <para>4: OnDisconnected callback endpoint with / at the beginning, with unique connection ID</para>
        /// </summary>
        public BWebSocketService(
            int _WSSServerPort,
            string _WSSCertificatePath,
            string _WSSCertificatePasswordPath,
            Tuple <string, Func <IBWebSocketClient> >[] _Endpoints,
            IBMemoryServiceInterface _MemoryService,
            Action <string> _ErrorMessageAction = null)
        {
            try
            {
                MemoryService = _MemoryService;

                WSSServerPort          = _WSSServerPort;
                WSSCertificatePath     = _WSSCertificatePath;
                WSSCertificatePassword = File.ReadAllText(_WSSCertificatePasswordPath).TrimEnd('\n').TrimEnd('\r');

                if (_Endpoints != null && _Endpoints.Length > 0)
                {
                    foreach (var _Endpoint in _Endpoints)
                    {
                        Endpoints.Add(_Endpoint);
                    }
                }
                else
                {
                    bInitializationSucceed = false;
                    return;
                }

                X509Cert = new X509Certificate2(WSSCertificatePath, WSSCertificatePassword);

                WSSServer = new WebSocketServer("wss://0.0.0.0:" + WSSServerPort);
                WSSServer.ListenerSocket.NoDelay  = true;
                WSSServer.RestartAfterListenError = true;
                WSSServer.Certificate             = X509Cert;
                FleckLog.LogAction = (Level, Message, Ex) =>
                {
                    switch (Level)
                    {
                    case LogLevel.Debug:
                        break;

                    case LogLevel.Error:
                        _ErrorMessageAction?.Invoke("WebSocket->Error: " + Message + ", Exception: " + Ex?.Message + ", Trace: " + Ex?.StackTrace);
                        break;

                    case LogLevel.Warn:
                        _ErrorMessageAction?.Invoke("WebSocket->Warning: " + Message + ", Exception: " + Ex?.Message + ", Trace: " + Ex?.StackTrace);
                        break;

                    default:
                        break;
                    }
                };

                WSSServer.Start(Socket =>
                {
                    Socket.OnOpen = () =>
                    {
                        if (Socket != null && !WSSConnections.ContainsKey(Socket))
                        {
                            if (Socket.IsAvailable && Socket.ConnectionInfo != null)
                            {
                                bool bFound = false;
                                foreach (var Endpoint in Endpoints)
                                {
                                    var IndexOfFirstQuestionMark = Socket.ConnectionInfo.Path.IndexOf('?');
                                    string PathWithoutParameters = IndexOfFirstQuestionMark >= 0 ? Socket.ConnectionInfo.Path.Substring(0, IndexOfFirstQuestionMark) : Socket.ConnectionInfo.Path;

                                    if (Endpoint.Item1 == PathWithoutParameters)
                                    {
                                        if (GetUniqueConnectionID(out long NewUniqueConnectionID, _ErrorMessageAction))
                                        {
                                            if (WSSConnections.TryAdd(Socket, new BWSSClient(Endpoint.Item1, NewUniqueConnectionID.ToString(), Endpoint.Item2, Socket.Send)))
                                            {
                                                bFound = true;
                                            }
                                        }
                                        break;
                                    }
                                }
                                if (!bFound)
                                {
                                    try
                                    {
                                        Socket.Close();
                                    }
                                    catch (Exception) { }
                                }
                            }
                            else
                            {
                                try
                                {
                                    Socket.Close();
                                }
                                catch (Exception) {}
                            }
                        }
                    };
                    Socket.OnClose = () =>
                    {
                        if (Socket != null)
                        {
                            if (WSSConnections.TryRemove(Socket, out BWSSClient OutClient))
                            {
                                OutClient?.OnClose();
                            }
                        }
                    };
                    Socket.OnMessage = (string Message) =>
                    {
                        if (Socket != null)
                        {
                            if (Socket.IsAvailable)
                            {
                                if (WSSConnections.TryGetValue(Socket, out BWSSClient OutClient))
                                {
                                    OutClient?.OnMessage(Message);
                                }
                            }
                            else
                            {
                                if (WSSConnections.TryRemove(Socket, out BWSSClient OutClient))
                                {
                                    OutClient?.OnClose();
                                }
                                try
                                {
                                    Socket.Close();
                                }
                                catch (Exception) { }
                            }
                        }
                    };
                });

                bInitializationSucceed = true;
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("BWebSocketService->Constructor: " + e.Message + ", Trace: " + e.StackTrace);
                bInitializationSucceed = false;
            }
        }