Esempio n. 1
0
        private static AvailableNetworkSessionCollection InternalFind(NetworkSessionType sessionType, IEnumerable <SignedInGamer> localGamers, NetworkSessionProperties searchProperties)
        {
            var config = new NetPeerConfiguration(NetworkSettings.GameAppId)
            {
                Port = 0, // Use any port
                AcceptIncomingConnections = false,
            };

            config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);

            var discoverPeer = new NetPeer(config);

            try
            {
                discoverPeer.Start();
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not start discover peer", e);
            }
            Debug.WriteLine("Discover peer started.");

            // Discover hosts
            if (sessionType == NetworkSessionType.SystemLink)
            {
                Debug.WriteLine("Sending local discovery request...");
                discoverPeer.DiscoverLocalPeers(NetworkSettings.Port);
            }
            else if (sessionType == NetworkSessionType.PlayerMatch || sessionType == NetworkSessionType.Ranked)
            {
                Debug.WriteLine("Sending discovery request to master server...");
                NetworkMasterServer.RequestHosts(discoverPeer);
            }
            else
            {
                throw new InvalidOperationException();
            }

            // Get list of answers
            var availableSessions = new List <AvailableNetworkSession>();

            var startTime = DateTime.Now;

            while (DateTime.Now - startTime <= DiscoveryTimeOut)
            {
                var msg = discoverPeer.ReadMessage();
                if (msg == null)
                {
                    Thread.Sleep((int)NoMessageSleep.TotalMilliseconds);
                    continue;
                }

                if (msg.MessageType == NetIncomingMessageType.DiscoveryResponse)
                {
                    Guid guid;
                    NetworkSessionPublicInfo publicInfo;
                    if (NetworkMasterServer.ParseExpectedResponseHeader(msg, MasterServerMessageType.RequestHosts) &&
                        NetworkMasterServer.ParseRequestHostsResponse(msg, out guid, out publicInfo))
                    {
                        AddAvailableNetworkSession(guid, publicInfo, localGamers, sessionType, searchProperties, availableSessions, tag: msg.SenderEndPoint);
                    }
                    else
                    {
                        Debug.WriteLine("Failed to parse local discovery response from " + msg.SenderEndPoint + ", ignoring...");
                    }
                }
                else if (msg.MessageType == NetIncomingMessageType.UnconnectedData)
                {
                    if (!msg.SenderEndPoint.Equals(NetworkMasterServer.ResolveEndPoint()))
                    {
                        Debug.WriteLine("Unconnected data not from master server recieved from " + msg.SenderEndPoint + ", ignoring...");
                    }
                    else
                    {
                        Guid guid;
                        NetworkSessionPublicInfo publicInfo;
                        if (NetworkMasterServer.ParseExpectedResponseHeader(msg, MasterServerMessageType.RequestHosts) &&
                            NetworkMasterServer.ParseRequestHostsResponse(msg, out guid, out publicInfo))
                        {
                            AddAvailableNetworkSession(guid, publicInfo, localGamers, sessionType, searchProperties, availableSessions);
                        }
                        else
                        {
                            Debug.WriteLine("Failed to parse master server discovery response from " + msg.SenderEndPoint + ", ignoring...");
                        }
                    }
                }
                else
                {
                    HandleLidgrenMessage(msg);
                }
                discoverPeer.Recycle(msg);
            }
            discoverPeer.Shutdown(string.Empty);
            Debug.WriteLine("Discovery peer shut down.");

            return(new AvailableNetworkSessionCollection(availableSessions));
        }
        private void ReceiveMessages()
        {
            NetIncomingMessage msg;

            while ((msg = peer.ReadMessage()) != null)
            {
                if (msg.MessageType == NetIncomingMessageType.DiscoveryRequest)
                {
                    Debug.WriteLine("Local discovery request received");

                    if (isHost)
                    {
                        UpdatePublicInfo();

                        NetworkMasterServer.SendRequestHostsResponse(peer, msg.SenderEndPoint, true, guid, publicInfo);
                    }
                }
                else if (msg.MessageType == NetIncomingMessageType.ConnectionApproval)
                {
                    if (!isHost)
                    {
                        throw new InvalidOperationException();
                    }

                    if (allowJoinInProgress || state == NetworkSessionState.Lobby)
                    {
                        byte machineId;
                        if (GetOpenPublicGamerSlots() > 0 && GetUniqueId(machineFromId, out machineId))
                        {
                            // Approved, create network machine
                            var machine = new NetworkMachine(this, false, false, machineId);
                            msg.SenderConnection.Tag = machine;
                            AddMachine(machine, msg.SenderConnection);

                            // Send approval to client containing unique machine id
                            var hailMsg = peer.CreateMessage();
                            hailMsg.Write(machineId);
                            msg.SenderConnection.Approve(hailMsg);
                        }
                        else
                        {
                            msg.SenderConnection.Deny(NetworkSessionJoinError.SessionFull.ToString());
                        }
                    }
                    else
                    {
                        msg.SenderConnection.Deny(NetworkSessionJoinError.SessionNotJoinable.ToString());
                    }
                }
                else if (msg.MessageType == NetIncomingMessageType.StatusChanged)
                {
                    var status = (NetConnectionStatus)msg.ReadByte();
                    Debug.WriteLine("Connection status updated: " + status + " (Reason: " + msg.ReadString() + ")");

                    if (status == NetConnectionStatus.Connected)
                    {
                        if (!isHost)
                        {
                            throw new InvalidOperationException("A client cannot accept new connections");
                        }
                        if (msg.SenderConnection.Tag == null)
                        {
                            throw new InvalidOperationException();
                        }

                        var machine = (NetworkMachine)msg.SenderConnection.Tag;

                        SendMachineConnectedMessage(machine, null);
                    }
                    else if (status == NetConnectionStatus.Disconnected)
                    {
                        if (msg.SenderConnection != null)
                        {
                            if (msg.SenderConnection.Tag == null)
                            {
                                throw new InvalidOperationException();
                            }

                            var machine = (NetworkMachine)msg.SenderConnection.Tag;

                            RemoveMachine(machine);

                            if (isHost)
                            {
                                SendMachineDisconnectedMessage(machine);
                            }
                            else
                            {
                                string reasonString;
                                NetworkSessionEndReason reason;
                                if (msg.ReadString(out reasonString) && Enum.TryParse(reasonString, out reason))
                                {
                                    End(reason);
                                }
                                else
                                {
                                    End(NetworkSessionEndReason.Disconnected);
                                }
                            }
                        }
                    }
                }
                else if (msg.MessageType == NetIncomingMessageType.Data)
                {
                    if (msg.SenderConnection.Tag == null)
                    {
                        throw new InvalidOperationException();
                    }
                    ReceiveMessage(msg, msg.DeliveryMethod, (NetworkMachine)msg.SenderConnection.Tag);
                }
                else if (msg.MessageType == NetIncomingMessageType.UnconnectedData)
                {
                    if (msg.SenderEndPoint.Equals(NetworkMasterServer.ResolveEndPoint()))
                    {
                        MasterServerMessageType   responseType;
                        MasterServerMessageResult responseResult;
                        if (NetworkMasterServer.ParseResponseHeader(msg, out responseType, out responseResult))
                        {
                            if (responseResult == MasterServerMessageResult.Ok)
                            {
                                if (responseType == MasterServerMessageType.RequestGeneralInfo)
                                {
                                    string generalInfo;
                                    if (NetworkMasterServer.ParseRequestGeneralInfoResponse(msg, out generalInfo))
                                    {
                                        masterServerGeneralInfo = generalInfo;
                                    }
                                }
                                else if (responseType == MasterServerMessageType.RegisterHost)
                                {
                                    isRegisteredAsHostWithMasterServer = true;
                                }
                                else if (responseType == MasterServerMessageType.UnregisterHost)
                                {
                                    isRegisteredAsHostWithMasterServer = false;
                                }
                            }
                            else
                            {
                                hasFailedMasterServerValidation = true;
                            }
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Unconnected data not from master server recieved from " + msg.SenderEndPoint + ", ignoring...");
                    }
                }
                else
                {
                    HandleLidgrenMessage(msg);
                }
                peer.Recycle(msg);

                if (IsDisposed)
                {
                    break;
                }
            }
        }