Chapter 10. Net

The Net namespace is one of the more interesting components of XNA Game Studio because it allows you to create networked, multiplayer games for use over system link or Xbox Live against other human players. The short gist of it is, yes, you can create a multiplayer game with a single Creators Club/App Hub account by writing and testing networking code on multiple PCs running the project in XNA Game Studio, with or without a connected Xbox 360. By developing with a mix of Windows and Xbox 360 machines, you can build a multiplayer game for the Creators Club/App Hub market without any extra licenses. This chapter focuses on covering the Net namespace as a quick reference. I will forego an example in this chapter because the subject is covered in more detail in Chapter 14, “Multiplayer Networking.”

This chapter covers these topics:

  • Net classes

  • Net Enumerations

Microsoft.Xna.Framework.Net Reference

The following pages provide a complete reference to the Net namespace. As was the case in previous reference chapters, inherited items are omitted from the list of properties, methods, etc., for each item.

Classes

Following are the classes found within the Net namespace.

AvailableNetworkSession

public sealed class AvailableNetworkSession

Describes a multiplayer session that can be joined. Use the NetworkSession class to get a list of AvailableNetworkSession instances. Typically, the results populate some type of user interface, displayed by the game. The user then chooses a session, and the game adds the player to the chosen session with a call to Join.

Public Properties

 

CurrentGamerCount

Gets the number of gamers in the session.

HostGamertag

Gets the gamertag of the session host.

OpenPrivateGamerSlots

Gets the number of private player slots.

OpenPublicGamerSlots

Gets the number of public player slots.

QualityOfService

Gets an estimate of the quality of network service between this local machine and the remote session.

SessionProperties

Gets any custom properties that have been attached to the session.

AvailableNetworkSessionCollection

public sealed class AvailableNetworkSessionCollection :
ReadOnlyCollection<AvailableNetworkSession>, IDisposable

Represents a collection of sessions available for joining.

GameEndedEventArgs

public class GameEndedEventArgs : EventArgs

Represents the arguments passed to a GameEnded event.

GamerJoinedEventArgs

public class GamerJoinedEventArgs : EventArgs

Represents the arguments passed to a GamerJoined event.

Public Properties

 

Gamer

Gets the gamer who just joined the session.

GamerLeftEventArgs

public class GamerLeftEventArgs : EventArgs

Represents the arguments passed to a GamerLeft event.

Public Properties

 

Gamer

Gets the gamer who just left the session.

GameStartedEventArgs

public class GameStartedEventArgs : EventArgs

Represents the arguments passed to a GameStarted event.

HostChangedEventArgs

public class HostChangedEventArgs : EventArgs

Represents the arguments passed to a HostChanged event.

Public Properties

 

NewHost

Gets the new host of the session.

OldHost

Gets the player who was the previous session host.

LocalNetworkGamer

public sealed class LocalNetworkGamer : NetworkGamer

Represents a local player in a network session.

Public Properties

 

IsDataAvailable

Determines whether there is incoming packet data for this player.

SignedInGamer

Gets the SignedInGamer instance for this SignedInGamer object.

Public Methods

 

EnableSendVoice

Specifies whether voice data should be sent to or received from the specified remote gamer.

ReceiveData

Reads the next incoming packet.

SendData

Sends data to a specified set of gamers in a network session.

SendPartyInvites

Sends game invitations to all party members who are not in the current game session.

NetworkGamer

public class NetworkGamer : Gamer

Represents a player in a network session. The NetworkSession class maintains a list of players in a network session. Some of the players may also be local players, who are represented in LocalNetworkGamer.

Public Properties

 

HasLeftSession

Indicates whether this gamer has left the session.

HasVoice

Determines whether the player has a voice headset.

Id

Gets a unique identifier that can be used to refer to this gamer in network packets.

IsGuest

Determines whether this gamer is logged in as a guest profile.

IsHost

Determines whether the player is the host of the multiplayer session.

IsLocal

Determines whether the player is playing on a local machine.

IsMutedByLocalUser

Determines whether the player is muted by one or more local users.

IsPrivateSlot

Determines whether the player occupies a reserved private session slot.

IsReady

Determines whether the gamer is ready to leave the lobby screen and begin gameplay.

IsTalking

Determines whether the gamer is currently sending voice data.

Machine

Gets an object representing the physical gaming machine this NetworkGamer is playing on.

RoundtripTime

Gets an estimate of the network latency involved in sending a packet round trip from the local machine to this gamer and back again.

Session

Gets the multiplayer session of the gamer.

NetworkMachine

public sealed class NetworkMachine

Represents a physical machine (such as single Xbox 360 console or a Windows-based computer) that is participating in a multiplayer session. It can be used to detect when more than one NetworkGamer is playing on the same actual machine.

Public Properties

 

Gamers

Gets a collection of all the gamers who are playing on this machine.

Public Methods

 

RemoveFromSession

Forcibly removes this machine from the session.

NetworkSession

public sealed class NetworkSession : IDisposable

Represents a multiplayer game session. An XNA Framework game can initiate only a single multiplayer session at a time. To start a multiplayer session, make a call to Create or use Find or BeginFind to search for and join an existing network session.

Public Fields

 

MaxPreviousGamers

Represents the maximum number of gamers that can be held in the PreviousGamers property.

MaxSupportedGamers

Maximum number of gamers supported in a session.

Public Properties

 

AllGamers

Gets the collection of gamers currently in the session.

AllowHostMigration

Gets or sets whether host migration is allowed. This can be read by any machine in the session, but can only be changed by the host. The default value is false, indicating that host migration is disabled.

AllowJoinInProgress

Gets or sets whether join-in-progress is allowed. If the host enables this setting, new machines will be able to join at any time. The default value is false, indicating that join-in-progress is disabled. AllowJoinInProgress can be read by any machine in the session, but can only be changed by the host.

BytesPerSecondReceived

Gets a performance counter recording the amount of data being received from the network.

BytesPerSecondSent

Gets a performance counter recording the amount of data being sent over the network.

Host

Gets the current host of the multiplayer session.

IsEveryoneReady

Determines whether all gamers are ready to enter the session.

IsHost

Determines whether this machine is the session host.

LocalGamers

Get the collection of local gamers for a multiplayer session.

MaxGamers

Gets or sets the maximum number of players able to join this multiplayer session.

PreviousGamers

A collection of previous gamers in the network session.

PrivateGamerSlots

Gets or sets the number of private slots reserved for gamers who join using an invitation.

RemoteGamers

Gets the collection of remote gamers for a multiplayer session.

SessionProperties

Gets any custom properties that have been attached to the session.

SessionState

Gets the current state of a multiplayer session.

SessionType

Gets the current multiplayer session type.

SimulatedLatency

Gets or sets the amount of simulated network latency.

SimulatedPacketLoss

Gets or sets the amount of simulated packet loss.

Public Methods

 

AddLocalGamer

Adds the specified local gamer profile to the network session.

BeginCreate

Starts hosting a new multiplayer session.

BeginFind

Starts a matchmaking query to search for available multiplayer sessions.

BeginJoin

Starts a join operation for the specified multiplayer session.

BeginJoinInvited

Starts joining an existing network session in response to an InviteAccepted notification event. Call EndJoinInvited to access the asynchronous method results.

Create

Hosts a new multiplayer session.

EndCreate

Gets the result from a BeginCreate asynchronous call.

EndFind

Gets the result from a BeginFind asynchronous call.

EndGame

Changes the session state from NetworkSessionState.Playing to NetworkSessionState.Lobby.

EndJoin

Gets the result from a BeginJoin asynchronous call.

EndJoinInvited

Gets the result from a BeginJoinInvited asynchronous call.

Find

Issues a matchmaking query, searching for available multiplayer sessions.

FindGamerById

Looks up the network gamer with the specified ID.

Join

Joins an existing multiplayer session.

JoinInvited

Joins the specified local gamers, along with the local machine, to an existing network session in response to an InviteAccepted notification event from a non-local session.

ResetReady

Resets the IsReady property of all session gamers.

StartGame

Changes the session state from NetworkSessionState.Lobby to NetworkSessionState.Playing.

Update

Updates the state of the multiplayer session.

Public Events

 

GameEnded

Occurs when the game moves from gameplay to the lobby.

GamerJoined

Occurs when a new player joins a multiplayer session.

GamerLeft

Occurs when a player leaves the multiplayer session.

GameStarted

Occurs when the game moves from the lobby into actual gameplay.

HostChanged

Occurs when the session host has changed.

InviteAccepted

Occurs when a user has accepted an invitation to join a network session.

SessionEnded

Occurs when the multiplayer session ends.

NetworkSessionEndedEventArgs

public class NetworkSessionEndedEventArgs : EventArgs

Represents the arguments passed to a SessionEnded event. These arguments are passed to event handlers when a session ends.

Public Properties

 

EndReason

Gets the reason for ending a session.

NetworkSessionJoinException

public class NetworkSessionJoinException : NetworkException

Thrown if an error was encountered while joining a session.

Public Properties

 

JoinError

Gets or sets a more detailed description of the session join failure.

Public Methods

 

GetObjectData

When overridden in a derived class, returns information about the exception.

NetworkSessionProperties

public class NetworkSessionProperties : IList<Nullable<int>>,
ICollection <Nullable<int>>, IEnumerable<Nullable<int>>, IEnumerable

Describes custom, game-specific information about a NetworkSession object. Examples of custom properties include specifying the current game mode or the current level selection. Use these properties to filter the results from a search using the Find or BeginFind methods.

Public Properties

 

Count

Gets the number of custom session properties.

Item

Gets or sets a custom session property value at the specified index.

Public Methods

 

GetEnumerator

Gets an enumerator for iterating over the custom property values.

Explicit Interface Implementations

 

System.Collections.Generic.ICollection{T}. IsReadOnly

Gets a value indicating whether the collection is read-only.

System.Collections.Generic.ICollection{T}.Add

This interface method is not supported by NetworkSessionProperties.

System.Collections.Generic.ICollection{T}.Clear

This interface method is not supported by NetworkSessionProperties.

System.Collections.Generic.ICollection{T}.Contains

Checks whether the collection contains the specified value.

System.Collections.Generic.ICollection{T}.CopyTo

Copies the contents of the collection to an array.

System.Collections.IEnumerable.GetEnumerator

Gets an enumerator for iterating over the custom property values.

System.Collections.Generic.IList{T}.IndexOf

Gets the index of the specified value.

System.Collections.Generic.IList{T}.Insert

This interface method is not supported by NetworkSessionProperties.

System.Collections.Generic.IList{T}.RemoveAt

This interface method is not supported by NetworkSessionProperties.

System.Collections.Generic.ICollection{T}.Remove

This interface method is not supported by NetworkSessionProperties.

PacketReader

public class PacketReader : BinaryReader

Provides common functionality for efficiently reading incoming network packets. Commonly, a multiplayer game should create a single PacketReader instance at startup and then reuse it whenever a packet needs to be read. To read the packet, you pass the PacketReader instance to ReceiveData and then use various Read methods to extract the data.

Public Properties

 

Length

Gets the length of the packet being read.

Position

Gets or sets the current packet read position.

Public Methods

 

ReadColor

Reads a Color value.

ReadDouble

Reads an 8-byte floating-point value.

ReadMatrix

Reads a Matrix value.

ReadQuaternion

Reads a Quaternion value.

ReadSingle

Reads a 4-byte floating-point value.

ReadVector2

Reads a Vector2 value.

ReadVector3

Reads a Vector3 value.

ReadVector4

Reads a Vector3 value.

PacketWriter

public class PacketWriter : BinaryWriter

Provides common functionality for efficiently formatting outgoing network packets.

Public Properties

 

Length

Gets the length of the packet being written.

Position

Gets or sets the current packet write position.

Public Methods

 

Write

Writes a value to an outgoing network packet.

QualityOfService

public sealed class QualityOfService

Describes the quality of the network connection between this machine and the host of a multiplayer session that was discovered with a matchmaking query.

Public Properties

 

AverageRoundtripTime

Gets the average (median) round-trip time of all the network packets that were sent during the quality-of-service measurement process.

BytesPerSecondDownstream

Gets an estimate of the available downstream network bandwidth from the session host to this machine, measured in bytes per second.

BytesPerSecondUpstream

Gets an estimate of the available upstream network bandwidth from this machine to the session host, measured in bytes per second.

IsAvailable

Checks whether this quality-of-service operation has completed.

MinimumRoundtripTime

Gets the minimum round-trip time of any network packet that was sent during the quality-of-service measurement process.

WriteLeaderboardsEventArgs

public sealed class WriteLeaderboardsEventArgs : EventArgs

Represents the arguments passed to a WriteArbitratedLeaderboard, WriteUnarbitratedLeaderboard, or WriteTrueSkill event.

Public Properties

 

Gamer

Gets the gamer whose statistics need to be written to the leaderboard.

IsLeaving

Indicates whether the player is leaving the session early.

Enumerations

Following are the enumerations in the Net namespace.

NetworkSessionEndReason

public enum NetworkSessionEndReason

Defines the reason a session ended.

ClientSignedOut

This client player has signed out of session.

HostEndedSession

The host left the session, removing all active players.

RemovedByHost

The host removed this client player from the session.

Disconnected

Network connectivity problems ended the session.

NetworkSessionJoinError

public enum NetworkSessionJoinError

Contains additional data about a NetworkSessionJoinException.

SessionNotFound

The session could not be found. Occurs if the session has ended after the matchmaking query but before the client joined, of if there is no network connectivity between the client and session host machines.

SessionNotJoinable

The session exists but is not joinable. Occurs if the session is in progress but does not allow gamers to join a session in progress.

SessionFull

The session exists but does not have any open slots for local signed-in gamers.

NetworkSessionState

public enum NetworkSessionState

Defines the different states of a multiplayer session.

Lobby

The local machine joins the session, waiting in the pregame lobby. The GameStarted event is raised when gameplay begins.

Playing

The local machine joins the session, currently in the middle of gameplay. The GameEnded event is raised when the session returns to the lobby.

Ended

The local machine has left the current session or the session has ended. The SessionEnded event is raised at this time. The event’s arguments describe the reason for the session ending.

NetworkSessionType

public enum NetworkSessionType

Defines the different types of multiplayer sessions.

Local

Does not involve any networking traffic, but can be used for split-screen gaming on a single Xbox 360 console. Creating a local network session may also make it easier to share code between local and online game modes.

LocalWithLeaderboards

Creates a local session with access to write to leaderboards on the Xbox Live servers. This local session type allows guests or other Xbox Live player profiles to join the session.

SystemLink

Connects multiple Xbox 360 consoles or computers over a local subnet. These machines do not require a connection to Xbox Live or any Xbox Live accounts. However, connection to machines on different subnets is not allowed. If you are a Creators Club developer testing your game, you can use this type to connect an Xbox 360 console to a computer. However, cross-platform networking is not supported in games distributed to non–Creators Club community players.

PlayerMatch

Uses the Xbox Live servers. This enables connection to other machines over the Internet. It requires an Xbox Live Silver Membership for Windows-based games or an Xbox Live Gold membership for Xbox 360 games. Games in development will also require an XNA Creators Club premium membership. While in trial mode, indie games downloaded from Xbox Live Marketplace will not have access to Xbox Live matchmaking.

Ranked

All session matches are ranked. This option is available only for commercial games that have passed Xbox Live certification. Due to the competitive nature of the gameplay, this session type does not support join-in-progress.

SendDataOptions

public enum SendDataOptions

Defines options for network packet transmission.

None

Sends the data with no guarantees. Packets of this type may be delivered in any order, with occasional packet loss. This is the most efficient option in terms of network bandwidth and machine resource usage. However, it is recommended only in situations where your game can recover from occasional packet loss.

Reliable

Sends the data with reliable delivery, but no special ordering. Packets of this type are re-sent until arrival at the destination. They may arrive out of order.

InOrder

Sends the data with guaranteed ordering, but without reliable delivery. Occasionally, packets of this type are not delivered. However, any delivered packets always arrive in the order in which they are sent. Use this option in situations where the transmitted value changes constantly. Old versions never arrive after a more recent version.

ReliableInOrder

Sends the data with reliability and arrival in the order originally sent. Packets of this type are re-sent until arrival and ordered internally. This means they arrive in the same order in which they were sent. In terms of network-bandwidth usage, this is the strongest and most expensive option. Use this only when arrival and ordering are essential. Commonly, a game uses this option for a small percentage of packets. The majority of gameplay data is sent using None or Reliable.

Chat

Indicates that this packet contains chat data, such as a player-to-player message string entered using the keyboard. To comply with international regulations, you must send such data without packet encryption. Therefore, you must use this flag to mark it. To maintain security, other game data should not use this flag. It is acceptable and efficient to mix encrypted and unencrypted data. If you send packets both with and without this flag within a single frame, both the encrypted and unencrypted data streams will be merged into a single wire packet. This option can be combined with either or both of the Reliable and InOrder flags. When you request in-order delivery for chat packets, they will be ordered relative to other chat packets, but they may arrive out of order with respect to other non-chat data.

Summary

The core networking and multiplayer features of XNA Game Studio are summarized in the Net namespace, reviewed in this chapter. We will spend quite a bit of time on this awesome subject in Chapter 14, where you will start small and build up to a fully playable networked game over system link and Xbox Live in the final chapter, using nothing more than an App Hub membership! In the meantime, refer to this chapter any time you need to look up details about the Net classes or enumerations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.17