Now that clients are connecting to the server, it would be nice to update the UI on the server side to indicate when a client has connected (and left, for that matter). However, currently no way to do this has been discussed. As luck would have it, there are two events you can hook to give you this information. In your initialization method for the server, you will need to add the following event hooks: connection.PlayerCreated += new PlayerCreatedEventHandler(OnPlayerCreated); connection.PlayerDestroyed += new PlayerDestroyedEventHandler(OnPlayerDestroyed); Whenever a player either joins or leaves the session, the appropriate event will be fired. The implementations of the event handlers are pretty similar as well. Add them from Listing 19.4 to your server application. Listing 19.4 Player Management Event Handlersprivate void OnPlayerCreated(object sender, PlayerCreatedEventArgs e) { try { string playerName = ((Server)sender).GetClientInformation (e.Message.PlayerID).Name; string newtext = string.Format ("Accepted new connection from {0}, UserID: 0x{1}", playerName, e.Message.PlayerID.ToString("x")); this.BeginInvoke(new AddTextCallback(AddText), new object[] { newtext }); } catch { /* Ignore this, probably the server */ } } private void OnPlayerDestroyed(object sender, PlayerDestroyedEventArgs e) { string newtext = string.Format ("DirectPlayer UserID: 0x{0} has left the session.", e.Message.PlayerID.ToString("x")); this.BeginInvoke(new AddTextCallback(AddText), new object[] { newtext }); } The player-destroyed handler is quite simple, as all it does is update the UI to notify you that the user has left the session. The player-created handler has a method that has never actually been discussed before, though. In the client's application, you set the client name with a call to SetClientInformation; in the server you retrieve this name with the call to GetClientInformation. When a server first starts a session, a default "hidden" player is created. Since there is no client associated with this player, the call to SetClientInformation will naturally fail. You can simply ignore that case for this example since it is expected.
|