02.02.2013 Views

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 22: Multi-player games using sockets<br />

is set. For the SockListener application we want <strong>to</strong> initialize a server socket. The dialog will only<br />

ever contain one of these, but first we need the IP address of the server. To get this we create a<br />

function called ‘GetServerIP’. This uses the API (Application Programming Interface) function,<br />

‘gethostname’. The purpose of this function is <strong>to</strong> return the host name in string format. Notice<br />

that unlike <strong>Flash</strong>, every variable has <strong>to</strong> be of a specified type, and every variable must be declared<br />

before use.<br />

After getting the name of the server, a structure HOSTENT is returned using the function<br />

‘gethostbyname’ passing the host name as a parameter. The HOSTENT structure contains details<br />

about the server including the IP address, which is s<strong>to</strong>red in the member h_addr. The host name<br />

is s<strong>to</strong>red in the member variable ‘m_cshostname’ for future use.<br />

1 BOOL CSockListenerDlg::GetServerIP()<br />

2 {<br />

3 HOSTENT *hs;<br />

4 UCHAR ch[4]={0};<br />

5<br />

6<br />

CString csInfo;<br />

7 ::gethostname((LPSTR)(LPCTSTR)m_cshostname, 50);<br />

8<br />

9<br />

hs = gethostbyname((LPSTR)(LPCTSTR)m_cshostname);<br />

10 memcpy(ch, hs->h_addr, 4);<br />

11 csInfo.Format("%s %d.%d.%d.%d", m_cshostname,<br />

12 ch[0], ch[1], ch[2], ch[3]);<br />

13<br />

14<br />

GetDlgItem(IDC_TEXT)->SetWindowText(csInfo);<br />

15<br />

16 }<br />

return TRUE;<br />

Listing 22.1<br />

Assuming that the IP address was successfully found, the server socket is created using the PORT<br />

defined by the constant PORT; in this example this is set <strong>to</strong> 5001 and the fact that the type of<br />

socket is a stream. The value of the PORT is set in file ‘stdafx.h’ which is part of this application<br />

and the value for the constant SOCK_STREAM is defined in the file ‘winsock.h’ which is a<br />

standard file included with Visual C++. Having created the server socket it is set <strong>to</strong> listening mode<br />

using the member function ‘Listen’.<br />

1 ////////////////////////////////////////////////////////////////////<br />

2 //<br />

3 // CSockListenerDlg message handlers<br />

4<br />

5 BOOL CSockListenerDlg::OnInitDialog()<br />

6 {<br />

349

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!