⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 326-328.html

📁 java game programming e-book
💻 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:Advanced Networking and Multiplayer Gaming Concepts</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,&nbsp;Macmillan Computer Publishing
    <br>
    <b>ISBN:</b>&nbsp;1571690433<b>&nbsp;&nbsp;&nbsp;Pub Date:</b>&nbsp;11/01/96</font>&nbsp;&nbsp;
</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=9//-->
<!--PAGES=326-328//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="322-326.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="328-331.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading20"></A><FONT COLOR="#000077">Creating the ChatServerThread Class</FONT></H4>
<P>This class is not too difficult to write, because it really doesn&#146;t do much. Hopefully, you remember how to create and use a ServerSocket from the last chapter, so we won&#146;t discuss all the details. This, of course, won&#146;t compile either, because we haven&#146;t written sClientGroup yet! Nevertheless, we should write it as if there were an sClientGroup and compile it later. Here is what sClientGroup.java should look like:
</P>
<!-- CODE //-->
<PRE>
import java.net.*;
import java.lang.*;
import sClientGroup;

public class ChatServerThread extends Thread &#123;
ServerSocket servSock = null;
sClientGroup group;

ChatServerThread() &#123;
       try &#123;
            servSock = new ServerSocket(1123);
        &#125; catch (Exception e) &#123;
            System.out.println("Could not initialize. Exiting.");
            System.exit(1);
        &#125;
System.out.println("Server successfully initialized. Waiting for
                  connection...");
group = new sClientGroup();
group.start();
&#125;
</PRE>
<!-- END CODE //-->
<P>Notice that the server attempts to listen on port 1123, in honor of the first four Fibonacci numbers. If this port is already in use on your system, you can change this value, but be sure you use the same number for the client. Here&#146;s the rest of the code:
</P>
<!-- CODE //-->
<PRE>
public void run() &#123;

while(servSock != null ) &#123;
Socket tempSock;
        try &#123;
       tempSock = servSock.accept();
       System.out.println("Received New Connection.");
       group.addClient( tempSock );
        &#125; catch (Exception e) &#123;
            System.out.println("New Connection Failure. Exiting.");
            System.exit(1);
        &#125;
&#125;
&#125;

public void finalize() &#123;
       try &#123;
              servSock.close();
       &#125; catch(Exception e);
       servSock = null;
&#125;
&#125;
</PRE>
<!-- END CODE //-->
<P>Our server here is very temperamental. If it receives any kind of networking error, it immediately exits. A commercial application would, of course, need to be far more robust, and do possible error-correcting steps. Luckily, we don&#146;t really have to worry about that at this point because these sorts of errors are relatively rare.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading21"></A><FONT COLOR="#000077">Creating the sClientGroup Class</FONT></H4>
<P>It&#146;s time to do the real work of this application. The object we are about to write is the one that must handle a whole group of clients and carry messages back and forth between them. Before we do this, we will discuss a little bit about the Vector class.
</P>
<H4 ALIGN="CENTER"><A NAME="Heading22"></A><FONT COLOR="#000077">The Vector Class</FONT></H4>
<P>A Vector is one of the wonderful Java utility classes (just like StringTokenizer). A Vector is an Object that is used to store other Objects. In this case, we are going to use it to hold a group of sClientThreads. Let&#146;s take a look at some of the important methods in java.util.Vector:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;new Vector(). This creates a new Vector object and initializes it.
<DD><B>&#149;</B>&nbsp;&nbsp;size(). This returns the number of objects stored in this Vector.
<DD><B>&#149;</B>&nbsp;&nbsp;elementAt(int n). This returns <I>n</I>th object (element).
<DD><B>&#149;</B>&nbsp;&nbsp;addElement(Object ob). This adds <I>ob</I> to the end of the list.
<DD><B>&#149;</B>&nbsp;&nbsp;removeElement(Object ob). This removes <I>ob</I> from the list.
</DL>
<H4 ALIGN="CENTER"><A NAME="Heading23"></A><FONT COLOR="#000077">The sClientGroup.java Startup File</FONT></H4>
<P>That should be enough to get started with the code. Here&#146;s the start of sClientGroup.java, which we won&#146;t be able to compile until we write sClientThread:
</P>
<!-- CODE //-->
<PRE>
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;

import sClientThread;

public class sClientGroup extends Thread &#123;
Vector theGroup;
sClientGroup() &#123;
theGroup = new Vector();
&#125;
&#125;
</PRE>
<!-- END CODE //-->
<P>OK, that&#146;s the start. It doesn&#146;t do anything, so let&#146;s add the first function, addClient(), which we called from ChatServerThread. All it needs to do is create a new sClientThread based on a Socket and then add it to <I>theGroup</I>, which is our Vector list. Note that when we create the sClientThread, we pass it the special keyword <I>this</I>, which always points to the current object. By passing <I>this</I> to the sClientThread, we allow for the Thread to call functions that are in sClientGroup. Here&#146;s how it goes:</P>
<!-- CODE SNIP //-->
<PRE>
public void addClient(Socket s) &#123;
sClientThread tempThread;
       tempThread = new sClientThread( s, this );
       theGroup.addElement( tempThread );
       tempThread.start();
&#125;
</PRE>
<!-- END CODE SNIP //-->
<P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="322-326.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="328-331.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -