Microsoft DirectX 9.0 SDK Update (Summer 2003) |
Once you have connected to a session, you can begin game play by sending messages to the other peers in the session for whom you have received a DPN_MSGID_CREATE_PLAYER message. This tutorial extends Tutorial 4 and discusses how to send messages. The complete sample code for this tutorial is included with the Microsoft® DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut05_Send.
Refer to the preceding tutorials for a discussion of the initial steps in the process:
When you run this tutorial sample, a window opens and you have the choice to either Host or Connect.
If you choose Host:
If you choose Connect:
You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address. When connected, you can send messages between the host and the client application.
Once the session is initiated, the peers manage the progress of the game by sending a stream of messages to each other. The content of the message is up to the application but typically includes such information as game state updates or player-to-player communication. Sending a message is straightforward. Select the player you want to send the message to, package your data in a buffer, and pass the data to the target player by calling IDirectPlay8Peer::SendTo. You also have the option of using a single IDirectPlay8Peer::SendTo call to broadcast a message to all players.
The following excerpt from the tutorial sample illustrates how to send a message to every player in the session.
DPN_BUFFER_DESC dpnBuffer; WCHAR wszData[256]; dpnBuffer.pBufferData = (BYTE*) wszData; dpnBuffer.dwBufferSize = 2 * (wcslen(wszData) + 1); hr = g_pDP->SendTo( DPNID_ALL_PLAYERS_GROUP, // dpnid &dpnBuffer, // pBufferDesc 1, // cBufferDesc 0, // dwTimeOut NULL, // pvAsyncContext NULL, // pvAsyncHandle DPNSEND_SYNC | DPNSEND_NOLOOPBACK ); // dwFlags
When another player sends you a message, your Microsoft DirectPlay® message handler receives a DPN_MSGID_RECEIVE message containing the data buffer.
The following excerpt from the tutorial sample illustrates a simple message handler for received messages.
//In the receiving player's message handler: HRESULT WINAPI DirectPlayMessageHandler(void *pvUserContext, DWORD dwMessageId, void *pMsgBuffer) { switch( dwMessageId ) { case DPN_MSGID_RECEIVE: { case DPN_MSGID_RECEIVE: { PDPNMSG_RECEIVE pMsg; pMsg = (PDPNMSG_RECEIVE) pMsgBuffer; //process message . . . break; } } } return(DPN_OK); }
If a DirectPlay peer object was successfully initialized, you should first close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.