public void CreateMatch()
 {
     if (Gamer.SignedInGamers.Count == 0 && !Guide.IsVisible)
     {
         Guide.ShowSignIn(1, false);
         return;
     }
     else if (Gamer.SignedInGamers.Count == 0)
     {
         return;
     }
     StateManager.NetworkData.LeaveSession();
     if (StateManager.NetworkData.AvailableSessions != null)
     {
         if (!StateManager.NetworkData.AvailableSessions.IsDisposed)
         {
             StateManager.NetworkData.AvailableSessions.Dispose();
         }
         StateManager.NetworkData.AvailableSessions = null;
     }
     LoadingScreen lScr = StateManager.AllScreens[ScreenType.LoadingScreen.ToString()] as LoadingScreen;
     lScr.Reset();
     lScr.UserCallback = new PGCGame.CoreTypes.Delegates.AsyncHandlerMethod(FinishLanSectorHost);
     lScr.LoadingText = "Hosting\n"+(StateManager.NetworkData.SessionType == NetworkSessionType.SystemLink ? "LAN" : "LIVE")+" sector...";
     lScr.ScreenFinished += new EventHandler(hosting_finish);
     //lScr.ScreenFinished += new EventHandler(lScr_ScreenFinished);
     NetworkSessionProperties netSession = new NetworkSessionProperties();
     netSession[(int)NetworkSessionPropertyType.SessionType] = (int)StateManager.NetworkData.SessionMode;
     NetworkSession.BeginCreate(StateManager.NetworkData.SessionType, new SignedInGamer[] { Gamer.SignedInGamers[0] }, 8, 0, netSession, lScr.Callback, null);
     StateManager.ScreenState = CoreTypes.ScreenType.LoadingScreen;
 }
Beispiel #2
0
        public void FindSession(NetworkSessionType sessionType, int maxLocalPlayers, NetworkSessionProperties properties)
        {
            // all sessions found
            AvailableNetworkSessionCollection availableSessions;
            // The session we'll join
            AvailableNetworkSession availableSession = null;

            availableSessions = NetworkSession.Find(sessionType, maxLocalPlayers, properties);

            // Get a session with available gamer slots
            foreach (AvailableNetworkSession  curSession in availableSessions)
            {
                int TotalSessionSlots = curSession.OpenPublicGamerSlots + curSession.OpenPrivateGamerSlots;
                if (TotalSessionSlots > curSession.CurrentGamerCount)
                {
                    availableSession = curSession;
                }
            }

            // if a session was found, connect to it
            if (availableSession != null)
            {
                networkHelper.session = NetworkSession.Join(availableSession);
            }
        }
Beispiel #3
0
        public void Find()
        {
            NetworkSessionProperties props = new NetworkSessionProperties();

            findResult = NetworkSession.BeginFind(NetworkSessionType.SystemLink,
                1, props, new AsyncCallback(GotResult), null);
            PendingFind = true;
        }
Beispiel #4
0
        public void Host()
        {
            if (netPlay.NetSession != null)
                netPlay.NetSession.Dispose();

            NetworkSessionProperties props = new NetworkSessionProperties();

            createResult = NetworkSession.BeginCreate(NetworkSessionType.SystemLink,
                1, 2, 0, props, new AsyncCallback(GotResult), null);
            PendingHost = true;
        }
Beispiel #5
0
        /// <summary>
        /// Converts a NetworkSessionProperties instance to the SessionProperties
        /// </summary>
        internal static SessionProperties ConvertFromLiveSessionProperties(NetworkSessionProperties networkSessionProperties)
        {
            if (networkSessionProperties == null)
                return null;

            var sessionProperties = new SessionProperties();

            for (int i = 0; i < networkSessionProperties.Count; i++)
            {
                sessionProperties[i] = networkSessionProperties[i];
            }

            return sessionProperties;
        }
Beispiel #6
0
        /// <summary>
        /// Converts a SessionProperties instance to the NetworkSessionProperties
        /// </summary>
        internal static NetworkSessionProperties ConvertToLiveSessionProperties(SessionProperties sessionProperties)
        {
            if (sessionProperties == null)
                return null;

            var networkSessionProperties = new NetworkSessionProperties();
            
            for (int i = 0; i < sessionProperties.Count; i++)
            {
                networkSessionProperties[i] = sessionProperties[i];
            }

            return networkSessionProperties;
        }
Beispiel #7
0
        public void CreateSession(NetworkSessionType sessionType, int maxLocalPlayers, int maxGamers, 
            int privateSlots, NetworkSessionProperties properties)
        {
            if (networkHelper.session == null)
            {
                networkHelper.session = NetworkSession.Create(sessionType, maxLocalPlayers,
                    maxGamers, privateSlots, properties);

                // If the host goes out, another machine will asume as a new host
                networkHelper.session.AllowHostMigration = true;
                // Allow players to join a game in progress
                networkHelper.session.AllowJoinInProgress = true;

                eventHandler.HookSessionEvents();
            }
        }
Beispiel #8
0
		public static NetworkSession Create (
         NetworkSessionType sessionType,			// Type of session being hosted.
         IEnumerable<SignedInGamer> localGamers,	// Maximum number of local players on the same gaming machine in this network session.
         int maxGamers,								// Maximum number of players allowed in this network session.  For Zune-based games, this value must be between 2 and 8; 8 is the maximum number of players supported in the session.
         int privateGamerSlots,						// Number of reserved private session slots created for the session. This value must be less than maximumGamers. 
         NetworkSessionProperties sessionProperties // Properties of the session being created.
		)
		{
			try
			{
				if ( maxGamers < 2 || maxGamers > 8 ) 
					throw new ArgumentOutOfRangeException( "Maximum number of gamers must be between 2 and 8."  );
				if ( privateGamerSlots < 0 || privateGamerSlots > maxGamers ) 
					throw new ArgumentOutOfRangeException( "Private session slots must be between 0 and maximum number of gamers."  );
			
				networkSessionType = sessionType;
			
				throw new NotImplementedException();
			}
			finally
			{
			}
		} 
Beispiel #9
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IAsyncResult CreateNetwork(Game game, NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool AllowHostMigration, bool AllowJoinInProgress)
        {
            SessionManager sessionManager = new SessionManager(game);

            IAsyncResult asyncResult = sessionManager.CreateSession(sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties);
            /*
            if (networkHelper.NetworkGameSession != null)
            {
                if (AllowHostMigration == true)
                    networkHelper.NetworkGameSession.AllowHostMigration = true;

                if (AllowJoinInProgress == true)
                    networkHelper.NetworkGameSession.AllowJoinInProgress = true;
                return asyncResult;
            }
            else
            {
                //throw new Exception("Session was not Created");
                return asyncResult;

            }*/
            return asyncResult;
        }
Beispiel #10
0
 private static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int hostGamer, int maxLocalGamers, NetworkSessionProperties searchProperties)
 {
     try
     {
         if (maxLocalGamers < 1 || maxLocalGamers > 4)
         {
             throw new ArgumentOutOfRangeException("maxLocalGamers must be between 1 and 4.");
         }
         List <AvailableNetworkSession> list = new List <AvailableNetworkSession>();
         MonoGamerPeer.Find(sessionType);
         return(new AvailableNetworkSessionCollection((IList <AvailableNetworkSession>)list));
     }
     finally
     {
     }
 }
Beispiel #11
0
 public static NetworkSession Create(NetworkSessionType sessionType, IEnumerable <SignedInGamer> localGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties)
 {
     try
     {
         return(NetworkSession.EndCreate(NetworkSession.BeginCreate(sessionType, localGamers, maxGamers, privateGamerSlots, sessionProperties, (AsyncCallback)null, (object)null)));
     }
     finally
     {
     }
 }
Beispiel #12
0
        public static IAsyncResult BeginFind(NetworkSessionType sessionType, IEnumerable <SignedInGamer> localGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
        {
            int hostingGamerIndex = NetworkSession.GetHostingGamerIndex(localGamers);

            return(NetworkSession.BeginFind(sessionType, hostingGamerIndex, 4, searchProperties, callback, asyncState));
        }
Beispiel #13
0
        /// <summary>
        /// Refreshes the current list of available sessions.
        /// </summary>
        /// <param name="searchParameters">Optional parameters to filter by.</param>
        public static void RefreshAvailableSessions(NetworkSessionProperties searchParameters = null)
        {
            AvailableSessions.Clear();

            if (HasActiveSession || availableAsync != null)
                return;

            availableAsync = null;

            try
            {
                AvailableNetworkSessionCollection availableSessions
                    = NetworkSession.Find(NetworkSessionType.SystemLink, MaxLocalGamers, searchParameters);
                foreach (AvailableNetworkSession session in availableSessions)
                    AvailableSessions.Add(new AvailableSession(session));
            }
            catch (Exception e)
            {
                ReportError(e.Message);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Creates a session with the given parameters.
 /// </summary>
 /// <param name="maxGamers">Maximum number of gamers allowed.</param>
 /// <param name="allowHostMigration">If host migration is allowed.</param>
 /// <param name="properties">Properties to initialize the session with.</param>
 /// <param name="initializeFunction">The optional function to call to initialize the session.</param>
 public static bool CreateSession(int maxGamers, bool allowHostMigration, NetworkSessionProperties properties, ActiveSession.ActiveSessionDelegate initializeFunction )
 {
     if (IsLocked)
         return false;
     #if DEBUG
     Log.Trace("Creating session...", 2.0f);
     #endif
     try
     {
         NetworkSession session = NetworkSession.Create(NetworkSessionType.SystemLink, MaxLocalGamers, maxGamers, 0, properties);
         session.AllowHostMigration = allowHostMigration;
         ActiveSession = new ActiveSession(session, initializeFunction);
         return true;
     }
     catch( Exception e)
     {
         ReportError(e.Message);
         ActiveSession.EndSession();
         return false;
     }
 }
Beispiel #15
0
 public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties)
 {
   return NetworkSession.EndFind(NetworkSession.BeginFind(sessionType, -1, maxLocalGamers, searchProperties, (AsyncCallback) null, (object) null));
 }
Beispiel #16
0
 private static IAsyncResult BeginFind(NetworkSessionType sessionType, int hostGamer, int maxLocalGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
   if (sessionType == NetworkSessionType.Local)
     throw new ArgumentException("NetworkSessionType cannot be NetworkSessionType.Local");
   if (maxLocalGamers < 1 || maxLocalGamers > 4)
     throw new ArgumentOutOfRangeException("maxLocalGamers must be between 1 and 4.");
   else
     return new NetworkSessionAsynchronousFind(NetworkSession.Find).BeginInvoke(sessionType, hostGamer, maxLocalGamers, searchProperties, callback, asyncState);
 }
Beispiel #17
0
        private void MGServer_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker     backgroundWorker  = sender as BackgroundWorker;
            NetPeerConfiguration peerConfiguration = new NetPeerConfiguration(MonoGamerPeer.applicationIdentifier);

            peerConfiguration.EnableMessageType((NetIncomingMessageType)32);
            peerConfiguration.EnableMessageType((NetIncomingMessageType)64);
            peerConfiguration.EnableMessageType((NetIncomingMessageType)2048);
            if (this.availableSession == null)
            {
                peerConfiguration.set_Port(MonoGamerPeer.port);
            }
            this.peer = new NetServer(peerConfiguration);
            ((NetPeer)this.peer).Start();
            this.myLocalAddress  = MonoGamerPeer.GetMyLocalIpAddress();
            this.myLocalEndPoint = new IPEndPoint(IPAddress.Parse(this.myLocalAddress), MonoGamerPeer.port);
            while (this.session.LocalGamers.Count <= 0)
            {
                Thread.Sleep(10);
            }
            if (this.availableSession != null)
            {
                if (!this.online)
                {
                    ((NetPeer)this.peer).Connect(this.availableSession.EndPoint);
                }
                else
                {
                    MonoGamerPeer.RequestNATIntroduction(this.availableSession.EndPoint, (NetPeer)this.peer);
                }
            }
            else if (this.online)
            {
                IPAddress address = NetUtility.Resolve(MonoGamerPeer.masterServer);
                if (address == null)
                {
                    throw new Exception("Could not resolve live host");
                }
                MonoGamerPeer.m_masterServer = new IPEndPoint(address, MonoGamerPeer.masterserverport);
                LocalNetworkGamer  localNetworkGamer = this.session.LocalGamers[0];
                NetOutgoingMessage message           = ((NetPeer)this.peer).CreateMessage();
                message.Write((byte)0);
                message.Write(this.session.AllGamers.Count);
                message.Write(localNetworkGamer.Gamertag);
                message.Write(this.session.PrivateGamerSlots);
                message.Write(this.session.MaxGamers);
                message.Write(localNetworkGamer.IsHost);
                message.Write(this.myLocalEndPoint);
                message.Write(((NetPeer)this.peer).get_Configuration().get_AppIdentifier());
                int[] propertyData = new int[this.session.SessionProperties.Count * 2];
                NetworkSessionProperties.WriteProperties(this.session.SessionProperties, propertyData);
                for (int index = 0; index < propertyData.Length; ++index)
                {
                    message.Write(propertyData[index]);
                }
                ((NetPeer)this.peer).SendUnconnectedMessage(message, MonoGamerPeer.m_masterServer);
            }
            do
            {
                NetIncomingMessage netIncomingMessage;
                while ((netIncomingMessage = ((NetPeer)this.peer).ReadMessage()) != null)
                {
                    NetIncomingMessageType messageType = netIncomingMessage.get_MessageType();
                    if (messageType <= 128)
                    {
                        if (messageType <= 8)
                        {
                            switch (messageType - 1)
                            {
                            case 0:
                                NetConnectionStatus connectionStatus = (NetConnectionStatus)(int)netIncomingMessage.ReadByte();
                                if (connectionStatus == 5)
                                {
                                    this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandGamerLeft(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier())));
                                }
                                if (connectionStatus == 3 && !this.pendingGamers.ContainsKey(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()))
                                {
                                    this.pendingGamers.Add(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier(), netIncomingMessage.get_SenderConnection());
                                    this.SendProfileRequest(netIncomingMessage.get_SenderConnection());
                                    break;
                                }
                                else
                                {
                                    break;
                                }

                            case 1:
                                break;

                            default:
                                if (messageType == 8)
                                {
                                    switch (netIncomingMessage.ReadByte())
                                    {
                                    case (byte)0:
                                        byte[] data = new byte[netIncomingMessage.get_LengthBytes() - 1];
                                        netIncomingMessage.ReadBytes(data, 0, data.Length);
                                        this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandReceiveData(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier(), data)));
                                        break;

                                    case (byte)3:
                                        string endPoint1 = netIncomingMessage.ReadString();
                                        try
                                        {
                                            IPEndPoint endPoint2 = MonoGamerPeer.ParseIPEndPoint(endPoint1);
                                            if (this.myLocalEndPoint.ToString() != endPoint2.ToString() && !this.AlreadyConnected(endPoint2))
                                            {
                                                ((NetPeer)this.peer).Connect(endPoint2);
                                                break;
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            break;
                                        }

                                    case (byte)4:
                                        if (this.pendingGamers.ContainsKey(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()))
                                        {
                                            this.pendingGamers.Remove(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier());
                                            netIncomingMessage.ReadInt32();
                                            string str = netIncomingMessage.ReadString();
                                            netIncomingMessage.ReadInt32();
                                            netIncomingMessage.ReadInt32();
                                            GamerStates gamerStates = (GamerStates)(netIncomingMessage.ReadInt32() & -2);
                                            this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandGamerJoined(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier())
                                            {
                                                GamerTag = str,
                                                State    = gamerStates
                                            }));
                                            break;
                                        }
                                        else
                                        {
                                            break;
                                        }

                                    case (byte)5:
                                        this.SendProfile(netIncomingMessage.get_SenderConnection());
                                        break;

                                    case (byte)6:
                                        GamerStates gamerStates1 = (GamerStates)(netIncomingMessage.ReadInt32() & -2);
                                        using (IEnumerator <NetworkGamer> enumerator = this.session.RemoteGamers.GetEnumerator())
                                        {
                                            while (enumerator.MoveNext())
                                            {
                                                NetworkGamer current = enumerator.Current;
                                                if (current.RemoteUniqueIdentifier == netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier())
                                                {
                                                    current.State = gamerStates1;
                                                }
                                            }
                                            break;
                                        }

                                    case (byte)7:
                                        NetworkSessionState networkSessionState = (NetworkSessionState)netIncomingMessage.ReadInt32();
                                        using (IEnumerator <NetworkGamer> enumerator = this.session.RemoteGamers.GetEnumerator())
                                        {
                                            while (enumerator.MoveNext())
                                            {
                                                NetworkGamer current = enumerator.Current;
                                                if (current.RemoteUniqueIdentifier == netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier() && (current.IsHost && networkSessionState == NetworkSessionState.Playing))
                                                {
                                                    this.session.StartGame();
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        else if (messageType != 32)
                        {
                            if (messageType == 128)
                            {
                                ;
                            }
                        }
                        else
                        {
                            LocalNetworkGamer  localNetworkGamer = this.session.LocalGamers[0];
                            NetOutgoingMessage message           = ((NetPeer)this.peer).CreateMessage();
                            message.Write(this.session.RemoteGamers.Count);
                            message.Write(localNetworkGamer.Gamertag);
                            message.Write(this.session.PrivateGamerSlots);
                            message.Write(this.session.MaxGamers);
                            message.Write(localNetworkGamer.IsHost);
                            int[] propertyData = new int[this.session.SessionProperties.Count * 2];
                            NetworkSessionProperties.WriteProperties(this.session.SessionProperties, propertyData);
                            for (int index = 0; index < propertyData.Length; ++index)
                            {
                                message.Write(propertyData[index]);
                            }
                            ((NetPeer)this.peer).SendDiscoveryResponse(message, netIncomingMessage.get_SenderEndpoint());
                        }
                    }
                    else if (messageType <= 512)
                    {
                        if (messageType == 256 || messageType == 512)
                        {
                            ;
                        }
                    }
                    else if (messageType != 1024 && messageType == 2048)
                    {
                        ((NetPeer)this.peer).Connect(netIncomingMessage.get_SenderEndpoint());
                    }
                }
                Thread.Sleep(1);
                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel  = true;
                    this.done = true;
                }
            }while (!this.done);
        }
Beispiel #18
0
        private NetworkSession(NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool isHost, int hostGamer, AvailableNetworkSession availableSession) : this()
        {
            if (sessionProperties == null)
            {
                throw new ArgumentNullException("sessionProperties");
            }

            _allGamers   = new GamerCollection <NetworkGamer>();
            _localGamers = new GamerCollection <LocalNetworkGamer>();
//			for (int x = 0; x < Gamer.SignedInGamers.Count; x++) {
//				GamerStates states = GamerStates.Local;
//				if (x == 0)
//					states |= GamerStates.Host;
//				LocalNetworkGamer localGamer = new LocalNetworkGamer(this, (byte)x, states);
//				localGamer.SignedInGamer = Gamer.SignedInGamers[x];
//				_allGamers.AddGamer(localGamer);
//				_localGamers.AddGamer(localGamer);
//
//				// We will attach a property change handler to local gamers
//				//  se that we can broadcast the change to other peers.
//				localGamer.PropertyChanged += HandleGamerPropertyChanged;
//
//			}

            _remoteGamers   = new GamerCollection <NetworkGamer>();
            _previousGamers = new GamerCollection <NetworkGamer>();
            hostingGamer    = null;

            commandQueue = new Queue <CommandEvent>();

            this.sessionType       = sessionType;
            this.maxGamers         = maxGamers;
            this.privateGamerSlots = privateGamerSlots;
            this.sessionProperties = sessionProperties;
            this.isHost            = isHost;
            if (isHost)
            {
                networkPeer = new MonoGamerPeer(this, null);
            }
            else
            {
                if (networkPeer == null)
                {
                    networkPeer = new MonoGamerPeer(this, availableSession);
                }
            }

            CommandGamerJoined gj = new CommandGamerJoined(hostGamer, this.isHost, true);

            commandQueue.Enqueue(new CommandEvent(gj));
        }
Beispiel #19
0
 private static IAsyncResult BeginFind(NetworkSessionType sessionType, int hostGamer, int maxLocalGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
     if (sessionType == NetworkSessionType.Local)
     {
         throw new ArgumentException("NetworkSessionType cannot be NetworkSessionType.Local");
     }
     if (maxLocalGamers < 1 || maxLocalGamers > 4)
     {
         throw new ArgumentOutOfRangeException("maxLocalGamers must be between 1 and 4.");
     }
     try
     {
         return(new NetworkSessionAsynchronousFind(NetworkSession.Find).BeginInvoke(sessionType, hostGamer, maxLocalGamers, searchProperties, callback, asyncState));
     }
     finally
     {
     }
 }
Beispiel #20
0
        public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, IEnumerable <SignedInGamer> localGamers, NetworkSessionProperties searchProperties)
        {
            int hostingGamerIndex = NetworkSession.GetHostingGamerIndex(localGamers);

            return(NetworkSession.EndFind(NetworkSession.BeginFind(sessionType, hostingGamerIndex, 4, searchProperties, (AsyncCallback)null, (object)null)));
        }
Beispiel #21
0
        private void MGServer_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            NetPeerConfiguration config = new NetPeerConfiguration(applicationIdentifier);

            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess);

            if (availableSession == null)
            {
                config.Port = port;
            }

            // create and start server
            peer = new NetServer(config);
            peer.Start();

            myLocalAddress = GetMyLocalIpAddress();

            IPAddress adr = IPAddress.Parse(myLocalAddress);

            myLocalEndPoint = new IPEndPoint(adr, port);

            // force a little wait until we have a LocalGamer otherwise things
            // break. This is the first item in the queue so it shouldnt take long before we
            // can continue.
            while (session.LocalGamers.Count <= 0)
            {
                Thread.Sleep(10);
            }

            if (availableSession != null)
            {
                if (!this.online)
                {
                    peer.Connect(availableSession.EndPoint);
                }
                else
                {
                    RequestNATIntroduction(availableSession.EndPoint, peer);
                }
            }
            else
            {
                if (this.online)
                {
                    IPAddress ipaddr = NetUtility.Resolve(masterServer);
                    if (ipaddr != null)
                    {
                        m_masterServer = new IPEndPoint(ipaddr, masterserverport);
                        LocalNetworkGamer localMe = session.LocalGamers [0];

                        NetOutgoingMessage om = peer.CreateMessage();

                        om.Write((byte)0);
                        om.Write(session.AllGamers.Count);
                        om.Write(localMe.Gamertag);
                        om.Write(session.PrivateGamerSlots);
                        om.Write(session.MaxGamers);
                        om.Write(localMe.IsHost);
                        om.Write(myLocalEndPoint);
                        om.Write(peer.Configuration.AppIdentifier);
                        // send up session properties
                        int[] propertyData = new int[session.SessionProperties.Count * 2];
                        NetworkSessionProperties.WriteProperties(session.SessionProperties, propertyData);
                        for (int x = 0; x < propertyData.Length; x++)
                        {
                            om.Write(propertyData [x]);
                        }
                        peer.SendUnconnectedMessage(om, m_masterServer);                          // send message to peer
                    }
                    else
                    {
                        throw new Exception("Could not resolve live host");
                    }
                }
            }

            // run until we are done
            do
            {
                NetIncomingMessage msg;
                while ((msg = peer.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.UnconnectedData:
                        break;

                    case NetIncomingMessageType.NatIntroductionSuccess:
#if !WINDOWS_PHONE
                        Game.Instance.Log("NAT punch through OK " + msg.SenderEndpoint);
#endif
                        peer.Connect(msg.SenderEndpoint);
                        break;

                    case NetIncomingMessageType.DiscoveryRequest:
                        //
                        // Server received a discovery request from a client; send a discovery response (with no extra data attached)
                        //
                        // Get the primary local gamer
                        LocalNetworkGamer localMe = session.LocalGamers [0];

                        NetOutgoingMessage om = peer.CreateMessage();

                        om.Write(session.RemoteGamers.Count);
                        om.Write(localMe.Gamertag);
                        om.Write(session.PrivateGamerSlots);
                        om.Write(session.MaxGamers);
                        om.Write(localMe.IsHost);
                        int[] propertyData = new int[session.SessionProperties.Count * 2];
                        NetworkSessionProperties.WriteProperties(session.SessionProperties, propertyData);
                        for (int x = 0; x < propertyData.Length; x++)
                        {
                            om.Write(propertyData [x]);
                        }

                        peer.SendDiscoveryResponse(om, msg.SenderEndpoint);
                        break;

                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        //
                        // Just print diagnostic messages to console
                        //
#if !WINDOWS_PHONE
                        Game.Instance.Log(msg.ReadString());
#endif
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                        if (status == NetConnectionStatus.Disconnected)
                        {
#if !WINDOWS_PHONE
                            Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " disconnected! from " + msg.SenderEndpoint);
#endif
                            CommandGamerLeft cgj  = new CommandGamerLeft(msg.SenderConnection.RemoteUniqueIdentifier);
                            CommandEvent     cmde = new CommandEvent(cgj);
                            session.commandQueue.Enqueue(cmde);
                        }
                        if (status == NetConnectionStatus.Connected)
                        {
                            //
                            // A new player just connected!
                            //
                            if (!pendingGamers.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
                            {
#if !WINDOWS_PHONE
                                Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected! from " + msg.SenderEndpoint);
#endif
                                pendingGamers.Add(msg.SenderConnection.RemoteUniqueIdentifier, msg.SenderConnection);
                                SendProfileRequest(msg.SenderConnection);
                            }
                            else
                            {
#if !WINDOWS_PHONE
                                Game.Instance.Log("Already have a connection for that user, this is probably due to both NAT intro requests working");
#endif
                            }
                        }

                        break;

                    case NetIncomingMessageType.Data:

                        NetworkMessageType mt = (NetworkMessageType)msg.ReadByte();
                        switch (mt)
                        {
                        case NetworkMessageType.Data:
                            byte[] data = new byte[msg.LengthBytes - 1];
                            msg.ReadBytes(data, 0, data.Length);
                            CommandEvent cme = new CommandEvent(new CommandReceiveData(msg.SenderConnection.RemoteUniqueIdentifier,
                                                                                       data));
                            session.commandQueue.Enqueue(cme);
                            break;

                        case NetworkMessageType.Introduction:

                            var introductionAddress = msg.ReadString();

                            try {
                                IPEndPoint endPoint = ParseIPEndPoint(introductionAddress);

                                if (myLocalEndPoint.ToString() != endPoint.ToString() && !AlreadyConnected(endPoint))
                                {
#if !WINDOWS_PHONE
                                    Game.Instance.Log("Received Introduction for: " + introductionAddress +
                                                      " and I am: " + myLocalEndPoint + " from: " + msg.SenderEndpoint);
#endif
                                    peer.Connect(endPoint);
                                }
                            } catch (Exception exc) {
#if !WINDOWS_PHONE
                                Game.Instance.Log("Error parsing Introduction: " + introductionAddress + " : " + exc.Message);
#endif
                            }

                            break;

                        case NetworkMessageType.GamerProfile:
#if !WINDOWS_PHONE
                            Game.Instance.Log("Profile recieved from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier));
#endif
                            if (pendingGamers.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
                            {
                                pendingGamers.Remove(msg.SenderConnection.RemoteUniqueIdentifier);
                                msg.ReadInt32();
                                string gamerTag = msg.ReadString();
                                msg.ReadInt32();
                                msg.ReadInt32();
                                GamerStates state = (GamerStates)msg.ReadInt32();
                                state &= ~GamerStates.Local;
                                CommandGamerJoined cgj = new CommandGamerJoined(msg.SenderConnection.RemoteUniqueIdentifier);
                                cgj.GamerTag = gamerTag;
                                cgj.State    = state;
                                CommandEvent cmde = new CommandEvent(cgj);
                                session.commandQueue.Enqueue(cmde);
                            }
                            else
                            {
#if !WINDOWS_PHONE
                                Game.Instance.Log("We received a profile for an existing gamer.  Need to update it.");
#endif
                            }
                            break;

                        case NetworkMessageType.RequestGamerProfile:
#if !WINDOWS_PHONE
                            Game.Instance.Log("Profile Request recieved from: " + msg.SenderEndpoint);
#endif
                            SendProfile(msg.SenderConnection);
                            break;

                        case NetworkMessageType.GamerStateChange:
                            GamerStates gamerstate = (GamerStates)msg.ReadInt32();
                            gamerstate &= ~GamerStates.Local;
#if !WINDOWS_PHONE
                            Game.Instance.Log("State Change from: " + msg.SenderEndpoint + " new State: " + gamerstate);
#endif
                            foreach (var gamer in session.RemoteGamers)
                            {
                                if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier)
                                {
                                    gamer.State = gamerstate;
                                }
                            }
                            break;

                        case NetworkMessageType.SessionStateChange:
                            NetworkSessionState sessionState = (NetworkSessionState)msg.ReadInt32();

                            foreach (var gamer in session.RemoteGamers)
                            {
                                if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier)
                                {
#if !WINDOWS_PHONE
                                    Game.Instance.Log("Session State change from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) +
                                                      " session is now: " + sessionState);
#endif
                                    if (gamer.IsHost && sessionState == NetworkSessionState.Playing)
                                    {
                                        session.StartGame();
                                    }
                                }
                            }

                            break;
                        }
                        break;
                    }
                }

                // sleep to allow other processes to run smoothly
                // This may need to be changed depending on network throughput
                Thread.Sleep(1);

                if (worker.CancellationPending)
                {
#if !WINDOWS_PHONE
                    Game.Instance.Log("worker CancellationPending");
#endif
                    e.Cancel = true;
                    done     = true;
                }
            } while (!done);
        }
Beispiel #22
0
 public static IAsyncResult BeginFind(NetworkSessionType sessionType, IEnumerable<SignedInGamer> localGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
   int hostingGamerIndex = NetworkSession.GetHostingGamerIndex(localGamers);
   return NetworkSession.BeginFind(sessionType, hostingGamerIndex, 4, searchProperties, callback, asyncState);
 }
Beispiel #23
0
 private NetworkSession(NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool isHost, int hostGamer)
   : this(sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer, (AvailableNetworkSession) null)
 {
 }
Beispiel #24
0
 public static IAsyncResult BeginFind(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
   return NetworkSession.BeginFind(sessionType, -1, 4, searchProperties, callback, asyncState);
 }
Beispiel #25
0
 private NetworkSession(NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool isHost, int hostGamer, AvailableNetworkSession availableSession)
   : this()
 {
   if (sessionProperties == null)
     throw new ArgumentNullException("sessionProperties");
   this._allGamers = new GamerCollection<NetworkGamer>();
   this._localGamers = new GamerCollection<LocalNetworkGamer>();
   this._remoteGamers = new GamerCollection<NetworkGamer>();
   this._previousGamers = new GamerCollection<NetworkGamer>();
   this.hostingGamer = (NetworkGamer) null;
   this.commandQueue = new Queue<CommandEvent>();
   this.sessionType = sessionType;
   this.maxGamers = maxGamers;
   this.privateGamerSlots = privateGamerSlots;
   this.sessionProperties = sessionProperties;
   this.isHost = isHost;
   this.hostGamerIndex = hostGamer;
   this.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandGamerJoined(hostGamer, this.isHost, true)));
 }
Beispiel #26
0
 public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, IEnumerable<SignedInGamer> localGamers, NetworkSessionProperties searchProperties)
 {
   int hostingGamerIndex = NetworkSession.GetHostingGamerIndex(localGamers);
   return NetworkSession.EndFind(NetworkSession.BeginFind(sessionType, hostingGamerIndex, 4, searchProperties, (AsyncCallback) null, (object) null));
 }
Beispiel #27
0
 public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, IEnumerable<SignedInGamer> localGamers, NetworkSessionProperties searchProperties)
 {
     throw new NotImplementedException();
 }
Beispiel #28
0
 private static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int hostGamer, int maxLocalGamers, NetworkSessionProperties searchProperties)
 {
   if (maxLocalGamers < 1 || maxLocalGamers > 4)
     throw new ArgumentOutOfRangeException("maxLocalGamers must be between 1 and 4.");
   else
     return new AvailableNetworkSessionCollection((IList<AvailableNetworkSession>) new List<AvailableNetworkSession>());
 }
Beispiel #29
0
 public static IAsyncResult BeginCreate(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, AsyncCallback callback, object asyncState)
 {
     throw new NotImplementedException();
 }
Beispiel #30
0
        /// <summary>
        /// Creates a session with the given parameters asynchronously.
        /// </summary>
        /// <param name="maxGamers">Maximum number of gamers allowed.</param>
        /// <param name="allowHostMigration">If host migration is allowed.</param>
        /// <param name="properties">Properties to initialize the session with.</param>
        /// <param name="initializeFunction">The optional function to call to initialize the session.</param>
        public static void CreateSessionAsync(int maxGamers, bool allowHostMigration, NetworkSessionProperties properties, ActiveSession.ActiveSessionDelegate initializeFunction, Action<bool> callback)
        {
            if (IsLocked)
            {
                if (callback != null)
                    callback(false);
                return;
            }
            #if DEBUG
            Log.Trace("Creating session...", 2.0f);
            #endif
            createAsyncAllowHostMigration = allowHostMigration;
            createAsyncFunction = initializeFunction;
            createAsyncCallback = callback;

            try
            {
                createAsync = NetworkSession.BeginCreate(NetworkSessionType.SystemLink, MaxLocalGamers, maxGamers, 0, properties, CreateAsyncFinished, null);
            }
            catch (Exception e)
            {
                ReportError(e.Message);
                if ( createAsyncCallback != null )
                    createAsyncCallback(false);
                CreateAsyncClear();
            }
        }
Beispiel #31
0
 public static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties)
 {
     throw new NotImplementedException();
 }
Beispiel #32
0
        /// <summary>
        /// Refreshes the current list of available sessions asynchronously.
        /// </summary>
        /// <param name="searchParameters">Optional parameters to filter by.</param>
        public static void RefreshAvailableSessionsAsync(NetworkSessionProperties searchParameters, Action<bool> callback)
        {
            if (HasActiveSession || availableAsync != null)
            {
                if ( callback != null )
                    callback(false);
                return;
            }

            availableCallback = callback;

            try
            {
                availableAsync = NetworkSession.BeginFind(NetworkSessionType.SystemLink, MaxLocalGamers, searchParameters, AvailableAsyncFinished, null);
            }
            catch (Exception e)
            {
                ReportError(e.Message);
                if ( availableCallback != null )
                    availableCallback(false);
                AvailableAsyncClear();
            }
        }
Beispiel #33
0
 public static IAsyncResult BeginFind(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
     return(NetworkSession.BeginFind(sessionType, -1, 4, searchProperties, callback, asyncState));
 }
Beispiel #34
0
        private static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, int hostGamer, bool isHost)
        {
            NetworkSession networkSession = (NetworkSession)null;

            try
            {
                if (sessionProperties == null)
                {
                    sessionProperties = new NetworkSessionProperties();
                }
                networkSession = new NetworkSession(sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer);
            }
            finally
            {
            }
            return(networkSession);
        }
Beispiel #35
0
 private static IAsyncResult BeginCreate(NetworkSessionType sessionType, int hostGamer, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, AsyncCallback callback, object asyncState)
 {
   if (maxLocalGamers < 1 || maxLocalGamers > 4)
     throw new ArgumentOutOfRangeException("Maximum local players must be between 1 and 4.");
   if (maxGamers < 2 || maxGamers > 32)
     throw new ArgumentOutOfRangeException("Maximum number of gamers must be between 2 and 32.");
   else
     return new NetworkSessionAsynchronousCreate(NetworkSession.Create).BeginInvoke(sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, hostGamer, true, callback, asyncState);
 }
Beispiel #36
0
 public static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties)
 {
   return NetworkSession.EndCreate(NetworkSession.BeginCreate(sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, (AsyncCallback) null, (object) null));
 }
Beispiel #37
0
 public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties)
 {
     return(NetworkSession.EndFind(NetworkSession.BeginFind(sessionType, -1, maxLocalGamers, searchProperties, (AsyncCallback)null, (object)null)));
 }
Beispiel #38
0
 public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties)
 {
     throw new NotImplementedException();
 }
Beispiel #39
0
 private static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, int hostGamer, bool isHost)
 {
   if (sessionProperties == null)
     sessionProperties = new NetworkSessionProperties();
   return new NetworkSession(sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer);
 }
Beispiel #40
0
 public static IAsyncResult BeginFind(NetworkSessionType sessionType, int maxLocalGamers, NetworkSessionProperties searchProperties, AsyncCallback callback, object asyncState)
 {
     throw new NotImplementedException();
 }
Beispiel #41
0
 public static IAsyncResult BeginCreate(NetworkSessionType sessionType, IEnumerable<SignedInGamer> localGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, AsyncCallback callback, object asyncState)
 {
   int hostingGamerIndex = NetworkSession.GetHostingGamerIndex(localGamers);
   return NetworkSession.BeginCreate(sessionType, hostingGamerIndex, 4, maxGamers, privateGamerSlots, sessionProperties, callback, asyncState);
 }
Beispiel #42
0
		internal static void FindResults (List<AvailableNetworkSession> networkSessions)
		{

			foreach (NetIncomingMessage im in discoveryMsgs) {

				AvailableNetworkSession available = new AvailableNetworkSession ();
				switch (im.MessageType) {
				case NetIncomingMessageType.DiscoveryResponse :                        
					int currentGameCount = im.ReadInt32 ();
					string gamerTag = im.ReadString ();
					int openPrivateGamerSlots = im.ReadInt32 ();
					int openPublicGamerSlots = im.ReadInt32 ();
					bool isHost = im.ReadBoolean ();

					NetworkSessionProperties properties = new NetworkSessionProperties ();
					int[] propertyData = new int[properties.Count * 2];
					for (int x = 0; x < propertyData.Length; x++) {
						propertyData [x] = im.ReadInt32 ();
					}

					NetworkSessionProperties.ReadProperties (properties, propertyData);
					available.SessionProperties = properties;

					available.SessionType = NetworkSessionType.SystemLink;
					available.CurrentGamerCount = currentGameCount;
					available.HostGamertag = gamerTag;
					available.OpenPrivateGamerSlots = openPrivateGamerSlots;
					available.OpenPublicGamerSlots = openPublicGamerSlots;
					available.EndPoint = im.SenderEndpoint;
					available.InternalEndpont = null;
					break;
				case NetIncomingMessageType.UnconnectedData :
					if (im.SenderEndpoint.Equals (m_masterServer)) {
						currentGameCount = im.ReadInt32 ();
						gamerTag = im.ReadString ();
						openPrivateGamerSlots = im.ReadInt32 ();
						openPublicGamerSlots = im.ReadInt32 ();
						isHost = im.ReadBoolean ();
						IPEndPoint hostInternal = im.ReadIPEndpoint ();
						IPEndPoint hostExternal = im.ReadIPEndpoint ();
						available.SessionType = NetworkSessionType.PlayerMatch;
						available.CurrentGamerCount = currentGameCount;
						available.HostGamertag = gamerTag;
						available.OpenPrivateGamerSlots = openPrivateGamerSlots;
						available.OpenPublicGamerSlots = openPublicGamerSlots;
						// its data from the master server so it includes the internal and external endponts
						available.EndPoint = hostExternal;
						available.InternalEndpont = hostInternal;
					}
					break;
				}


				networkSessions.Add (available);

			}
		}
Beispiel #43
0
 public static IAsyncResult BeginCreate(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, AsyncCallback callback, object asyncState)
 {
   return NetworkSession.BeginCreate(sessionType, -1, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, callback, asyncState);
 }