Пример #1
0
        /// <summary>
        /// Stops server
        /// </summary>
        /// <returns></returns>
        public void Stop()
        {
            TcpServerSocket nullSocket = null;
            var             socket     = Interlocked.Exchange(ref _socketServer, nullSocket);

            socket?.ServerStop();
        }
Пример #2
0
        /// <summary>
        /// Starts server async
        /// </summary>
        /// <returns></returns>
        public async Task <bool> StartAsync()
        {
            // do nothing if already started
            if (_socketServer != null)
            {
                _logger.LogInformation("Server already started.");
                return(true);
            }

            // init socket
            var socket = new TcpServerSocket(_createDataProcessorFunc, _serverConfig, _loggerFactory);

            // bind events
            if (_eventHandler != null)
            {
                socket.ClientConnectedAction    = _eventHandler.HandleClientConnected;
                socket.ClientDisconnectedAction = _eventHandler.HandleClientDisconnected;
                socket.ServerStartedAction      = _eventHandler.HandleServerStarted;
                socket.ServerStoppedAction      = _eventHandler.HandleServerStopped;
                socket.ServerStartFailureAction = _eventHandler.HandleServerStartFailure;

                // receive and action response
                socket.MsgReceivedAction = (data) =>
                {
                    var rsp = _eventHandler.HandleReceivedData(data);
                    if (rsp != null)
                    {
                        SendToClient(data.ClientId, rsp);
                    }
                };

                socket.MsgSentAction = _eventHandler.HandleSentData;
            }

            // start server
            bool status = await socket.ServerStart();

            // set server
            if (status)
            {
                Interlocked.Exchange(ref _socketServer, socket);
            }

            // return
            return(status);
        }