private async void StopServer()
 {
     ServerStatusChanged?.Invoke(this, false);
     await Dispatcher.InvokeAsync(() =>
     {
         ServerButton.Content = "Start Server";
     });
 }
Esempio n. 2
0
        /// <summary>
        ///     Update server provisioning status.
        /// </summary>
        /// <param name="serverIngressChanged">
        ///     A <see cref="ServerStatusChanged"/> message describing the change.
        /// </param>
        /// <returns>
        ///     A <see cref="Task"/> representing the operation.
        /// </returns>
        async Task UpdateServerProvisioningStatus(ServerStatusChanged serverProvisioningNotification)
        {
            if (serverProvisioningNotification == null)
            {
                throw new ArgumentNullException(nameof(serverProvisioningNotification));
            }

            Log.Debug("Updating provisioning status for server {ServerId} due to {NotificationType} notification...",
                      serverProvisioningNotification.ServerId,
                      serverProvisioningNotification.GetType().Name
                      );

            using (IAsyncDocumentSession session = DocumentStore.OpenAsyncSession())
            {
                DatabaseServer server = await session.LoadAsync <DatabaseServer>(serverProvisioningNotification.ServerId);

                if (server == null)
                {
                    Log.Warning("Received ServerStatusChanged notification for non-existent server (Id:{ServerId}).",
                                serverProvisioningNotification.ServerId
                                );

                    return;
                }

                Log.Debug("Existing provisioning status for server {ServerId} is {Action}:{Status}:{Phase}.",
                          server.Id,
                          server.Action,
                          server.Status,
                          server.Phase
                          );

                ProvisioningAction action = server.Action;

                if (serverProvisioningNotification.Status.HasValue)
                {
                    server.Status = serverProvisioningNotification.Status.Value;

                    switch (server.Status)
                    {
                    case ProvisioningStatus.Ready:
                    case ProvisioningStatus.Error:
                    {
                        server.Action = ProvisioningAction.None;
                        server.Phase  = ServerProvisioningPhase.None;

                        break;
                    }

                    case ProvisioningStatus.Deprovisioned:
                    {
                        session.Delete(server);

                        break;
                    }
                    }
                }

                if (serverProvisioningNotification.Phase.HasValue)
                {
                    server.Phase = serverProvisioningNotification.Phase.Value;
                }

                Log.Debug("New provisioning status for server {ServerId} is {Action}:{Status}:{Phase}.",
                          server.Id,
                          server.Action,
                          server.Status,
                          server.Phase
                          );

                server.AddProvisioningEvent(serverProvisioningNotification.Messages);

                await session.SaveChangesAsync();
            }

            Log.Debug("Updated provisioning status for server {ServerId}.", serverProvisioningNotification.ServerId);
        }
Esempio n. 3
0
 internal void UpdateDispatchConnectionStatus(ConnectionStatus status)
 {
     ServerStatus = status;
     ServerStatusChanged.Raise();
 }
        partial void ImplDispatchRead()
        {
            if (DispatchClient == null)
            {
                return;
            }

            var messages = m_messages;

            _lastDispatchSize = DispatchClient.ReadMessages(messages);
            // ReSharper disable once ForCanBeConvertedToForeach
            for (int i = 0; i < messages.Count; i++)
            {
                var msgType = messages[i].MessageType;
                var msg     = NetMessage.GetMessage(messages[i].Data.Length);
                messages[i].Clone(msg);
                msg.Sender = messages[i].SenderConnection;
                DispatchClient.Recycle(messages[i]);

                if (msgType == NetIncomingMessageType.Data)
                {
                    if (Server != null)
                    {
                        Server.ConsumeData(msg);
                    }
                    else
                    {
                        Debug.LogWarning("Received server data when not connected");
                    }
                }
                else if (msgType == NetIncomingMessageType.DebugMessage)
                {
                    Debug.Log(msg.ReadString());
                }
                else if (msgType == NetIncomingMessageType.WarningMessage)
                {
                    var str = msg.ReadString();
                    if (!str.StartsWith("Received unhandled library message Acknowledge"))
                    {
                        Debug.LogWarning(str);
                    }
                }
                else if (msgType == NetIncomingMessageType.StatusChanged)
                {
                    var status       = (NetConnectionStatus)msg.ReadByte();
                    var statusReason = msg.ReadString();
                    if (status == NetConnectionStatus.Connected)
                    {
                        var serverConn = DispatchClient.ServerConnection;
                        if (serverConn == null)
                        {
                            throw new NullReferenceException("Could not get server connection after connected");
                        }
                        var remsg = serverConn.RemoteHailMessage;
                        if (remsg == null)
                        {
                            throw new NullReferenceException("Could not get room guid");
                        }
                        byte[] gid;
                        if (!remsg.ReadBytes(16, out gid))
                        {
                            throw new Exception("Could not read room guid");
                        }
                        RoomId = new Guid(gid);
                        Debug.Log($"Connected to dispatcher. Id is {RoomId}");
                        Server = new Server(this)
                        {
                            Connection = serverConn
                        };
                    }
                    else if (status == NetConnectionStatus.Disconnected)
                    {
                        Server = null;
                        RoomId = Guid.Empty;
                        Debug.Log("Disconnected from dispatcher");
                    }
                    else
                    {
                        Debug.Log($"DConn ServerStatus: {status}, {statusReason}");
                    }
                    ServerStatus = status.ToPNet();
                    ServerStatusChanged?.Invoke();
                }
                else if (msgType == NetIncomingMessageType.Error)
                {
                    Debug.LogException(new Exception(msg.ReadString())
                    {
                        Source = "Room.Lidgren.ImplementationQueueRead [Lidgren DispatchClient Error]"
                    });                                                                                                                                     //this should really never happen...
                }
                else
                {
                    Debug.LogWarning($"Unknown message type {msgType} from server");
                }

                NetMessage.RecycleMessage(msg);
            }
            messages.Clear();
        }
 private void StartServer()
 {
     ServerStatusChanged?.Invoke(this, true);
     ServerButton.Content = "Stop Server";
 }
        private async void ConnectCallback(IAsyncResult ar)
        {
            var client = ar.AsyncState as TcpClient;

            try
            {
                if (client != _serverClient)
                {
                    throw new Exception("TcpClient Mismatch");
                }

                client.EndConnect(ar);
                Debug.Log("Authenticating with server");

                using (var networkStream = client.GetStream())
                {
                    await PerformHail(networkStream);

                    var        buffer        = new byte[1024];
                    NetMessage dataBuffer    = null;
                    var        bufferSize    = 0;
                    var        lengthBuffer  = new byte[2];
                    var        bytesReceived = 0;
                    int        readBytes;


                    var authMessages = new Queue <NetMessage>();
                    while (!_shutdownQueued)
                    {
                        readBytes = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                        if (readBytes > 0)
                        {
                            var readMessage = NetMessage.GetMessages(buffer, readBytes, ref bytesReceived,
                                                                     ref dataBuffer, ref lengthBuffer, ref bufferSize, authMessages.Enqueue);
                            if (readMessage >= 1)
                            {
                                break;
                            }
                        }
                        if (!client.Connected)
                        {
                            return;
                        }
                    }

                    if (authMessages.Count == 0)
                    {
                        throw new Exception("Could not read auth result");
                    }
                    var authMsg = authMessages.Dequeue();

                    var auth = authMsg.ReadBoolean();
                    authMsg.ReadPadBits();
                    if (!auth)
                    {
                        string reason;
                        if (!authMsg.ReadString(out reason))
                        {
                            reason = "Not authorized";
                        }
                        Debug.LogError("Could not connect to server. {0}", reason);
                        ServerStatus = ConnectionStatus.FailedToConnect;
                        ServerStatusChanged.TryRaise(Debug.Logger);
                        return;
                    }
                    Guid guid;
                    if (!authMsg.ReadGuid(out guid))
                    {
                        throw new Exception("Could not read room guid");
                    }

                    RoomId = guid;
                    Debug.Log("Connected to dispatcher. Id is {0}", RoomId);
                    Server = new Server(this)
                    {
                        NetworkStream = networkStream, TcpClient = client
                    };
                    ServerStatus = ConnectionStatus.Connected;
                    ServerStatusChanged.TryRaise(Debug.Logger);

                    //and drain the rest of messages that might have come after the auth
                    while (authMessages.Count > 0)
                    {
                        EnqueueMessage(authMessages.Dequeue());
                    }

                    while (!_shutdownQueued)
                    {
                        readBytes = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                        if (readBytes > 0)
                        {
                            NetMessage.GetMessages(buffer, readBytes, ref bytesReceived, ref dataBuffer,
                                                   ref lengthBuffer, ref bufferSize, EnqueueMessage);
                        }
                        if (!client.Connected)
                        {
                            return;
                        }
                    }
                }
            }
            catch (ObjectDisposedException ode)
            {
                if (!_shutdownQueued)
                {
                    Debug.LogException(ode, "{0} disposed when it shouldn't have", ode.ObjectName);
                }
            }
            catch (IOException ioe)
            {
                if (!(ioe.InnerException is SocketException))
                {
                    Debug.LogException(ioe);
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
                ServerStatus = ConnectionStatus.Disconnected;
                ServerStatusChanged.TryRaise(Debug.Logger);
            }
        }
Esempio n. 7
0
 private void OnServerStatusChanged(ServerStatusEventArgs eArgs)
 {
     ServerStatusChanged?.Invoke(this, eArgs);
 }