📄 304-306.html
字号:
<HTML>
<HEAD>
<META name=vsisbn content="1571690433"><META name=vstitle content="Black Art of Java Game Programming"><META name=vsauthor content="Joel Fan"><META name=vsimprint content="Sams"><META name=vspublisher content="Macmillan Computer Publishing"><META name=vspubdate content="11/01/96"><META name=vscategory content="Web and Software Development: Programming, Scripting, and Markup Languages: Java"><TITLE>Black Art of Java Game Programming:Implementing a High Score Server on a Network</TITLE>
<!-- HEADER --><STYLE type="text/css"> <!-- A:hover { color : Red; } --></STYLE><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><script><!--function displayWindow(url, width, height) { var Win = window.open(url,"displayWindow",'width=' + width +',height=' + height + ',resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></script><SCRIPT><!--function popUp(url) { var Win = window.open(url,"displayWindow",'width=400,height=300,resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></SCRIPT><script language="JavaScript1.2"><!--function checkForQuery(fm) { /* get the query value */ var i = escape(fm.query.value); if (i == "") { alert('Please enter a search word or phrase'); return false; } /* query is blank, dont run the .jsp file */ else return true; /* execute the .jsp file */}//--></script></HEAD><BODY>
<TABLE border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=75 valign=top>
<img src="../1571690433.gif" width=60 height=73 alt="Black Art of Java Game Programming" border="1">
</td>
<td align="left">
<font face="arial, helvetica" size="-1" color="#336633"><b>Black Art of Java Game Programming</b></font>
<br>
<font face="arial, helvetica" size="-1"><i>by Joel Fan</i>
<br>
Sams, Macmillan Computer Publishing
<br>
<b>ISBN:</b> 1571690433<b> Pub Date:</b> 11/01/96</font>
</td>
</tr>
</table>
<P>
<!--ISBN=1571690433//-->
<!--TITLE=Black Art of Java Game Programming//-->
<!--AUTHOR=Joel Fan//-->
<!--AUTHOR=Eric Ries//-->
<!--AUTHOR=Calin Tenitchi//-->
<!--PUBLISHER=Macmillan Computer Publishing//-->
<!--IMPRINT=Sams//-->
<!--CHAPTER=8//-->
<!--PAGES=304-306//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="301-303.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="306-309.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading39"></A><FONT COLOR="#000077">Creating a New Socket</FONT></H4>
<P>All of the networking code is contained in the getScoreData() method. Currently, this method returns a string of data, but let’s change it. Here’s the first part:
</P>
<!-- CODE //-->
<PRE>
String getScoreData() {
Socket s;
DataInputStream ds;
PrintStream ps;
String temp = null;
try {
s = new Socket("localhost",2357);
ds = new DataInputStream(s.getInputStream());
ps = new PrintStream(s.getOutputStream());
} catch (Exception e) {
return null;
}
</PRE>
<!-- END CODE //-->
<P>This part creates a new socket, called <I>s</I>, that tries to connect to host <I>localhost</I> on port 2357. <I>localhost</I> always refers to the computer that the applet is running on, so we use it for testing purposes. Eventually you will want to change this to reflect the real address of your server. Port 2357 is used here, partly to honor the first four prime numbers, but mainly because no other service is using it.</P>
<H4 ALIGN="LEFT"><A NAME="Heading40"></A><FONT COLOR="#000077">Establishing the Connection</FONT></H4>
<P>The first <I>try</I> block attempts to connect to the server and create new Input and Output streams. If any of this fails, we return <I>null</I>. Notice that we don’t really need to know what happened; our client aborts and tries again later. If the client was successful in creating a connection and opening streams, we proceed to the next part of the code. This part constitutes the first part of our <I>protocol</I>. Our protocol is very simple. The client sends commands to the server in the form “command::parameter,” and the server processes these commands as they come. The server will wait until the client sends “bye” before terminating the connection. This type of interaction is called <I>client-driven</I>, because it is the client who decides when communication will begin and end.</P>
<H4 ALIGN="LEFT"><A NAME="Heading41"></A><FONT COLOR="#000077">Updating and Requesting Information: The HighScore Protocol</FONT></H4>
<P>To handle high scores, we are only going to need two commands: <I>update</I> and <I>request</I>. These constitute the protocol that we are using. Keep in mind that this protocol is completely arbitrary. Here’s how we implement the <I>update</I> command:</P>
<!-- CODE SNIP //-->
<PRE>
StringTokenizer st;
try {
if ( updateStr != null) {
st = new StringTokenizer( updateStr , "|");
while (st.hasMoreTokens())
ps.println("update::"+st.nextToken());
updateStr = "";
}
</PRE>
<!-- END CODE SNIP //-->
<P>This code block sends each high score in the <I>updateStr</I> string and then resets <I>updateStr</I>. Next, we complete the second part of the communication:</P>
<!-- CODE SNIP //-->
<PRE>
ps.println("request::" + lastCheck);
temp = ds.readLine().trim();
ps.println("bye");
}
catch (Exception e) {
return null;
}
</PRE>
<!-- END CODE SNIP //-->
<P>Once all the updates are complete, we request any new data that has been received since the last time we checked (which we store in <I>lastCheck</I>). The server must respond with something, because the readLine() method (used to read in from our InputStream) is a method that <I>blocks</I>.</P>
<H4 ALIGN="LEFT"><A NAME="Heading42"></A><FONT COLOR="#000077">Understanding Blocking</FONT></H4>
<P>A method that blocks will not return until it is complete. These methods are dangerous, because if they never complete, the program could hang (freeze and never come back). This is one of the advantages of running the networking in a thread. Even in the unlikely event that the thread did hang, only the thread would be affected and the main program (the game and the HighScoreManager) could continue.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading43"></A><FONT COLOR="#000077">Terminating the Link</FONT></H4>
<P>Once the server responds to the <I>request</I> command, we tell the server “bye”. We again catch any exceptions that may have been generated, but we just return <I>null</I> and try again later. Now that our conversation with the server is finished, we need to tidy up. First, we display any data we got from the server to the System.out stream, which will print it out in the Appletviewer window. This is useful for debugging, but should be left out of the final version of your program. Next, we close the streams that we were using to communicate with the server, and then we close the Socket connection. This time we really ignore any errors, because we already have the data we want, which we return with</P>
<!-- CODE //-->
<PRE>
System.out.println("Got: "+temp);
try {
ds.close();
ps.close();
s.close();
} catch (Exception e);
return temp;
}
</PRE>
<!-- END CODE //-->
<P>The HighScoreManager class is finally complete. Unfortunately, we cannot test it until we have a server written. However, you can compile and run the testApp, and notice that, even though there is no server, it still works just fine. This was one of our stated objectives when we started, so it’s nice to know we have achieved it!
</P>
<H3><A NAME="Heading44"></A><FONT COLOR="#000077">Creating a Server Application</FONT></H3>
<P>At long last it is time to write our server code. Earlier, we said that one of the advantages to our client was that it could be used with any kind of server. Because you probably want to learn more about Java, and because it is perhaps the single easiest language for writing servers in, we are going to implement a Java server. However, this should not be regarded as the only way to do it.
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="301-303.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="306-309.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -