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

📄 ch18.htm

📁 21天学会用JAVA开发网络游戏 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 287 KB 书籍等级: 整理时间: 2004-1
💻 HTM
📖 第 1 页 / 共 3 页
字号:
In doing so, you'll have reliable, reusable code that can easily
be applied to provide functionality specific to a particular game
communication protocol.
<P>
As you learned earlier, the primary purpose of sockets is to provide
a channel of communication through a particular port. You also
learned that sockets have associated input and output streams
that actually handle the details of transferring information via
the socket. Even though the standard Java socket classes provide
much of this support, some code still must be handled on your
end; this is the code you're going to focus on at this point.
<P>
The first layer of code necessary to facilitate network communications
comes in the form of a socket helper class that handles the details
of initializing a socket and managing the associated data streams.
The <TT><FONT FACE="Courier">SocketAction</FONT></TT> class was
developed by Greg Turner to help ease the pain in establishing
a communication channel using Java sockets. The <TT><FONT FACE="Courier">SocketAction</FONT></TT>
class is derived from <TT><FONT FACE="Courier">Thread</FONT></TT>
so that it has its own thread of execution. Let's start by looking
at the member variables of <TT><FONT FACE="Courier">SocketAction</FONT></TT>,
which follow:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">private DataInputStream inStream = null;
<BR>
protected PrintStream&nbsp;&nbsp;&nbsp;outStream = null;<BR>
private Socket&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;socket
= null;</FONT></TT>
</BLOCKQUOTE>
<P>
The first two members, <TT><FONT FACE="Courier">inStream</FONT></TT>
and <TT><FONT FACE="Courier">outStream</FONT></TT>, are the input
and output streams used to receive and send data through the socket.
The third member variable, <TT><FONT FACE="Courier">socket</FONT></TT>,
is the socket object itself.
<P>
The constructor for <TT><FONT FACE="Courier">SocketAction</FONT></TT>
takes a <TT><FONT FACE="Courier">Socket</FONT></TT> object as
its only parameter:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">public SocketAction(Socket sock) {<BR>
&nbsp;&nbsp;super(&quot;SocketAction&quot;);<BR>
&nbsp;&nbsp;try {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;inStream = new DataInputStream(new<BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BufferedInputStream(sock.getInputStream(),
1024));<BR>
&nbsp;&nbsp;&nbsp;&nbsp;outStream = new PrintStream(new<BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BufferedOutputStream(sock.getOutputStream(),
1024), true);<BR>
&nbsp;&nbsp;&nbsp;&nbsp;socket = sock;<BR>
&nbsp;&nbsp;}<BR>
&nbsp;&nbsp;catch (IOException e) {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Couldn't initialize
SocketAction: &quot; + e);<BR>
&nbsp;&nbsp;&nbsp;&nbsp;System.exit(1);<BR>
&nbsp;&nbsp;}<BR>
}</FONT></TT>
</BLOCKQUOTE>
<P>
The constructor creates the buffered data streams and initializes
the <TT><FONT FACE="Courier">socket</FONT></TT> member variable
with the <TT><FONT FACE="Courier">Socket</FONT></TT> object passed
in. If there was a problem in initializing the streams, the constructor
detects it by using the <TT><FONT FACE="Courier">catch</FONT></TT>
clause. Note that if there is an error in creating the streams,
something is seriously wrong, which explains why the entire program
exits.
<P>
The <TT><FONT FACE="Courier">send</FONT></TT> and <TT><FONT FACE="Courier">receive</FONT></TT>
methods are possibly the most useful methods in <TT><FONT FACE="Courier">SocketAction</FONT></TT>,
even though they contain very little code:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">public void send(String s) {<BR>
&nbsp;&nbsp;outStream.println(s);<BR>
}<BR>
<BR>
public String receive() throws IOException {<BR>
&nbsp;&nbsp;return inStream.readLine();<BR>
}</FONT></TT>
</BLOCKQUOTE>
<P>
The <TT><FONT FACE="Courier">send</FONT></TT> method simply sends
a string out over the socket connection by using the output data
stream. Similarly, the <TT><FONT FACE="Courier">receive</FONT></TT>
method receives a string by using the input data stream.
<P>
The <TT><FONT FACE="Courier">closeConnections</FONT></TT> method
simply closes the socket:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">public void closeConnections() {<BR>
&nbsp;&nbsp;try {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;socket.close();<BR>
&nbsp;&nbsp;&nbsp;&nbsp;socket = null;<BR>
&nbsp;&nbsp;}<BR>
&nbsp;&nbsp;catch (IOException e) {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Couldn't close
socket: &quot; + e);<BR>
&nbsp;&nbsp;}<BR>
}</FONT></TT>
</BLOCKQUOTE>
<P>
The <TT><FONT FACE="Courier">isConnected</FONT></TT> method verifies
that the input and output streams, as well as the <TT><FONT FACE="Courier">socket</FONT></TT>
object, are valid:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">public boolean isConnected() {<BR>
&nbsp;&nbsp;return ((inStream != null) &amp;&amp; (outStream !=
null) &amp;&amp; (socket != null));<BR>
}<BR>
Finally, the finalize method closes the socket as an added safety
precaution:<BR>
protected void finalize () {<BR>
&nbsp;&nbsp;if (socket != null) {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;try {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;socket.close();<BR>
&nbsp;&nbsp;&nbsp;&nbsp;}<BR>
&nbsp;&nbsp;&nbsp;&nbsp;catch (IOException e) {<BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Couldn't
close socket: &quot; + e);<BR>
&nbsp;&nbsp;&nbsp;&nbsp;}<BR>
&nbsp;&nbsp;&nbsp;&nbsp;socket = null;<BR>
&nbsp;&nbsp;}<BR>
}</FONT></TT>
</BLOCKQUOTE>
<P>
And that's all there is to the <TT><FONT FACE="Courier">SocketAction</FONT></TT>
class. That wasn't too bad, was it? As you saw, the <TT><FONT FACE="Courier">SocketAction</FONT></TT>
class is pretty elementary. Nevertheless, its simple function
of providing a clean management class for sockets and their associated
streams will make life much easier tomorrow when you build a complete
network game.
<H2><A NAME="Summary"><B><FONT SIZE=5 COLOR=#FF0000>Summary</FONT></B></A>
</H2>
<P>
Today you broke away from the confines of programming for a single
user and moved into the world of network programming. You learned
that Java makes network programming surprisingly easy by providing
standard classes that hide most of the nastiness typically associated
with network programming. You began the lesson with some network
fundamentals, progressing onward to learn all about sockets and
how to use them. You then finished the lesson by developing a
reusable socket class that provides much of the overhead involved
in network communications.
<P>
Even though little of today's lesson had anything to do with game
programming specifically, you learned enough about Java network
programming to move on to tomorrow's lesson, which does deal with
game programming. In fact, tomorrow's lesson is entirely devoted
to converting the Connect4 game from <A HREF="ch16.htm" >Day 16</A>'s
lesson into a multiplayer network game playable over the Internet.
<H2><A NAME="QA"><B><FONT SIZE=5 COLOR=#FF0000>Q&amp;A</FONT></B></A>
<BR>
</H2>

<TABLE>
<TR VALIGN=TOP><TD WIDTH=50><B>Q</B></TD><TD><B>Why is the client/server paradigm so important in Java network programming?</B>
</TD></TR>
<TR VALIGN=TOP><TD WIDTH=50><B>A</B></TD><TD>The client/server model was integrated into Java because it has proven time and again to be superior to other networking approaches. By dividing the act of serving data from the act of viewing and working with 
data, the client/server approach provides network developers with the freedom to implement a wide range of solutions to common network problems.
</TD></TR>
<TR VALIGN=TOP><TD WIDTH=50><B>Q</B></TD><TD><B>Does the client/server strategy really make sense for games?</B>
</TD></TR>
<TR VALIGN=TOP><TD WIDTH=50><B>A</B></TD><TD>Based on the traditional role of a server strictly providing information to a &quot;dumb&quot; client, the answer is no. When it comes to games, however, the concept of what the clients and server are 
responsible for changes somewhat. For example, a game server is responsible for receiving client player events and dispatching them to the other players. In turn, the clients are responsible for generating and sending the events to the server, as well as 
updating themselves based on other player events received from the server. When you view the client/server model from this admittedly altered perspective, it makes complete sense for games.
</TD></TR>
<TR VALIGN=TOP><TD WIDTH=50><B>Q</B></TD><TD><B>Why aren't datagram sockets suitable for network game communications?</B>
</TD></TR>
<TR VALIGN=TOP><TD WIDTH=50><B>A</B></TD><TD>The primary reason is speed, because you have no way of knowing when information transferred through a datagram socket will reach its destination. Admittedly, you don't really know for sure when stream socket 
data will get to its destination either, but you can rest assured it will be faster than with the datagram socket. Also, datagram socket transfers have the additional complexity of requiring you to reorganize the incoming data, which is an unnecessary and 
time-consuming annoyance for games.
</TD></TR>
</TABLE>
<P>
<H2><A NAME="Workshop"><B><FONT SIZE=5 COLOR=#FF0000>Workshop</FONT></B></A>
</H2>
<P>
The Workshop section provides questions and exercises to help
you get a firmer grasp on the material you learned today. Try
to answer the questions and at least think about the exercises
before moving on to tomorrow's lesson. You'll find the answers
to the questions in appendix A, &quot;Quiz Answers.&quot;
<H3><A NAME="Quiz"><B>Quiz</B></A></H3>
<OL>
<LI>What is a port?
<LI>What is the significance of using sockets for network communications?
<LI>What is the difference between stream sockets and datagram
sockets?
<LI>What's the big deal about writing a reusable socket class?
</OL>
<H3><A NAME="Exercises"><B>Exercises</B></A></H3>
<OL>
<LI>If you have a dedicated Internet connection, find out what
your numeric IP address is.
<LI>Try out some networked Java applets and see if you can figure
out how they are using Java sockets. Note: You can find many networked
Java applets at the Gamelan Web site (<TT><A HREF="http://www.gamelan.com">http://www.gamelan.com</A></TT>).
<LI>Spend some time relaxing, because tomorrow's lesson dives
straight into developing a complete network game.
</OL>
<P>
<HR WIDTH="100%"></P>

<CENTER><P><A HREF="ch17.htm"><IMG SRC="pc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="index.htm"><IMG SRC="hb.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="#CONTENTS"><IMG SRC="cc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="ch19.htm"><IMG 
SRC="nc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A></P></CENTER>

<P>
<HR WIDTH="100%"></P>

</BODY>
</HTML>

⌨️ 快捷键说明

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