📄 ch28.htm
字号:
{<BR>
121 System.out.println("Whoops
no data at URL:"); }<BR>
122 }<BR>
123 } //run<BR>
124<BR>
125 } // class l28</FONT></TT>
</BLOCKQUOTE>
<HR>
<H3><A NAME="AQuickNoteAboutJava"><B>A Quick Note About Java</B></A>
</H3>
<P>
The Java programming language was developed at Sun Microsystems
Inc., Mountain View, California, by a group headed by James Gosling.
Java is a platform-independent, object-oriented language developed
primarily for use in household appliances. Java's usefulness extends
far beyond the initial intended use for developing it. Java appeared
at the same time as the World Wide Web (WWW) and was used by Sun
to develop WebRunner, a Web browser written entirely in Java.
(WebRunner was later renamed HotJava to avoid copyright problems.)
<P>
The Java Programming Language is very similar to, but much simpler
than, C++. Numbers and Boolean types serve as basic building blocks
for developing Java classes for object-oriented programming. Programmers
can create their own objects as classes. All classes in Java are
restricted to single-level inheritance only, because a class in
Java may only inherit from one class at a time. Abstract classes
in Java allow definitions of interfaces to permit multiple inheritance.
<P>
A Java <I>applet</I> is the result of running a Java compiler
on Java source code. Basically, in order to create a Java applet,
you need to have a Java Developer's Kit (JDK) on your system.
You can get a JDK for your machine from the Web site <TT><A HREF="http://www.javasoft.com/" tppabs="http://www.javasoft.com/">http://www.javasoft.com</A></TT>.
Included in a JDK distribution are compilers, documentation, and
source code for some sample applets that folks were kind enough
to donate for use, with limited copyright restrictions of course,
to the general computing community.
<P>
A Java source file can consist of several objects to implement
a certain set of functionality. The source code for an applet
when run through a Java compiler, <TT><FONT FACE="Courier">javac</FONT></TT>,
produces one or more <TT><FONT FACE="Courier">.Class</FONT></TT>
files, one for each type of object defined in the source file.
Each <TT><FONT FACE="Courier">.Class</FONT></TT> file is a series
of byte codes that are then referred to as "applets."
<P>
Applets reside on servers and are downloaded to clients when referenced
via a URL. Applets execute on remote sites under the auspices
of the browser that downloaded them. The address space and code
execution are modeled under a process known as the Java Virtual
Machine (JVM). The JVM describes how to implement Java applet
code and addresses issues regarding the ways to parse the byte
codes in an applet. Java is designed to be secure and robust enough
to prevent any applet's byte code's instructions to compromise
the client machine's system. By using the JVM model, byte codes
can be verified by <TT><FONT FACE="Courier">javac</FONT></TT>
to ensure that the resulting applet will not compromise system
integrity.
<P>
Java has support for multithreaded applications built into the
language. A browser running an applet can manage multiple threads
for a Java applet. Java threads are mapped by the browser into
the underlying operating system threads if the underlying system
supports it. Java-enabled browsers are designed and built for
each type of platform, such as Windows NT, 95, Macintosh, and
UNIX workstations.
<P>
Java also has support for network communication via the use of
TCP/IP or UDP sockets as well as with the use of URLs. In essence,
Java is a distributed language because Java applets can retrieve
data from any accessible node on the Internet. The permissions
available for a Java applet to access a file on the Internet can
be the same as those of the browser running the applet. Java applets
cannot have file access permissions that are greater than that
of their host browser for security reasons. Items accessed via
URLs include other HTML pages containing applets, raw files or
images, or links to other sites. Socket support under Java is
implemented using Berkeley (BSD) Socket Extensions.
<P>
For more information about programming in Java, please consult
the books in the section "For More Information on How to
Program in Java," later in this chapter.
<P>
Line 18 of Listing 28.2 starts a thread for the applet and declares
the <TT><FONT FACE="Courier">l28</FONT></TT> class. The Java program
gets the parameters to itself in lines 26 and 35. A <TT><FONT FACE="Courier">TextArea</FONT></TT>
(<TT><FONT FACE="Courier">ta</FONT></TT>) widget is declared and
added to the applet for the applet to display the incoming data.
<P>
Lines 26 and 32 show the code to extract the two input parameters
to the applet: <TT><FONT FACE="Courier">URL</FONT></TT> and <TT><FONT FACE="Courier">DELTA</FONT></TT>.
The <TT><FONT FACE="Courier">URL</FONT></TT> parameter is a string
containing the URL of where the data is located. The <TT><FONT FACE="Courier">DELTA</FONT></TT>
parameter is used to determine the time interval between successive
tries to extract the data. Default values are used when incoming
values are absurd or absent.
<P>
The <TT><FONT FACE="Courier">start()</FONT></TT> and <TT><FONT FACE="Courier">stop()</FONT></TT>
functions in lines 63 and 74 are called when the applet thread
starts and stops. The code in line 63 is called when a background
thread is created in the applet to do socket communication. The
subroutine in line 74 is called when the thread stops executing.
<P>
The bulk of the work is done in the <TT><FONT FACE="Courier">run()</FONT></TT>
subroutine in line 84, where the running thread connects to the
server in lines 95 to 97, extracts the data in the <TT><FONT FACE="Courier">while</FONT></TT>
loop in line 99, and then displays the received text in a text
area for the applet in line 102.
<P>
If there is an exception, it's of the type <TT><FONT FACE="Courier">IOException</FONT></TT>
and is caught at line 104, where a message is displayed on the
system status bar. The try-and-catch exception-handling mechanism
shown in lines 94 to 105 to fetch data is very common in Java
applet source code. The code in line 105 notifies the applet user
of exceptions like missing data or a bad URL value. The text area
actually updates the screen in line 112 with the <TT><FONT FACE="Courier">repaint()</FONT></TT>
call.
<P>
The loop is repeated starting from the section in line 117 to
fetch the next updated URL.
<P>
Once you have typed the code for the applet, you have to compile
it with the <TT><FONT FACE="Courier">javac</FONT></TT> compiler.
The Java applet is compiled to a <TT><FONT FACE="Courier">l28.class</FONT></TT>
with the following command:
<BLOCKQUOTE>
<TT><FONT FACE="Courier">javac l28.java</FONT></TT>
</BLOCKQUOTE>
<P>
The result of the command is a file called <TT><FONT FACE="Courier">l28.class</FONT></TT>
in the same directory. The prefix of the file and the class name
must be the same.
<P>
To use the applet in your HTML document, you have to use <TT><FONT FACE="Courier"><APPLET></FONT></TT>
and <TT><FONT FACE="Courier"></APPLET></FONT></TT> tags.
A sample usage is shown Listing 28.3.
<HR>
<BLOCKQUOTE>
<B>Listing 28.3. HTML page for using an applet to get text from
a server.<BR>
</B>
</BLOCKQUOTE>
<BLOCKQUOTE>
<TT><FONT FACE="Courier"> 1 <HTML><BR>
2 <BODY><BR>
3 <TITLE><BR>
4 Test<BR>
5 </TITLE><BR>
6 <H1> Test the applet to recover text
from server </H1><BR>
7 <applet code=l28.class width=300 height=400>
<BR>
8 <param name=URL value="http://ikra.com/tst.txt">
<BR>
9 <param name=DELTA value="10000">
<BR>
10 </applet><BR>
11 </BODY><BR>
12 </HTML></FONT></TT>
</BLOCKQUOTE>
<HR>
<P>
The code in line 7 shows how to include the applet code. The <TT><FONT FACE="Courier">width</FONT></TT>
and <TT><FONT FACE="Courier">height</FONT></TT> of the applet
are required parameters. The applet will not load if you do not
specify the <TT><FONT FACE="Courier">height</FONT></TT> and <TT><FONT FACE="Courier">width</FONT></TT>.
Line 8 sets the parameter <TT><FONT FACE="Courier">URL</FONT></TT>
to the applet and gives it a value of a complete URL. You can
specify relative URLs as well. Line 9 specifies a second parameter
for the time interval between updates as a string. The interval
can be specified as a string, but this way you'll see how to use
code in the applet to convert from a string to an <TT><FONT FACE="Courier">int</FONT></TT>.
The applet is closed out at line 10 with the <TT><FONT FACE="Courier"></applet></FONT></TT>
tag.
<P>
At line 117 of Listing 28.2, the program sleeps for the <TT><FONT FACE="Courier">DELTA</FONT></TT>
period specified. As just seen with I/O handling, this sleep call
also catches the exception of the type <TT><FONT FACE="Courier">InterruptedException</FONT></TT>
in cases of errors. Note that the sleep time in applets is in
milliseconds, whereas in Perl it's in seconds.
<P>
The <TT><FONT FACE="Courier">run()</FONT></TT> function loops
forever until the applet is destroyed by the user selecting another
HTML page.
<P>
As stated earlier, this chapter is not about teaching you to write
Java applets. Instead, this chapter shows you how it's possible
to interface with applets using CGI. The method shown in this
section is a bit crude in that the applet has to wake up and fetch
a document every time. Even cruder is the fact that the Perl script
at the other end has to open a file and then write to and close
it every so many seconds. You might consider keeping the file
open at all times in the Perl server script.
<P>
Another alternative to the scheme shown here is to use UNIX system
facilities to use sockets.
<H2><A NAME="UsingCGIandSockets"><B><FONT SIZE=5 COLOR=#FF0000>Using
CGI and Sockets</FONT></B></A></H2>
<P>
The second example of using Perl and Java together involves using
sockets for client/server communication. The server is written
in Perl, and the client is a Java applet on a client browser.
<P>
The approach to using sockets over files has the obvious advantage
of speed and more efficient use of system services. Of course,
your advantage is minimized a lot if you are echoing what you
write to the socket back onto the disk.
<P>
Also, Perl is portable to platforms that might not support sockets.
For example, Windows-based systems might not have Winsock loaded
correctly, or they might have the wrong version loaded, with which
they can run the browser but cannot access the socket's features.
In such a case where sockets are not supported on your server
side (a rare but true possibility), the first method of using
URLs alone will have to do.
<P>
The server application is pretty straightforward. It binds itself
to a port and listens for a connection. After getting a connection,
the server in this example sends 1,000 data items back to the
connecting client. Each data item sent back has an identifier
that is set to the current time. The identifier is often referred
to as the time stamp for this packet. (See Listing 28.4.)
<P>
The server in this example can be extended to use the <TT><FONT FACE="Courier">fork</FONT></TT>
system call and handle requests via children. The sample shown
here simply bails out after it's done. For a discussion of how
this server works, refer to <A HREF="ch12.htm" tppabs="http://www.mcp.com/815097600/0-672/0-672-30891-6/ch12.htm" >Chapter 12</A>.
See Listing 28.4 for a sample Perl server that simply listens
to a socket and, on receiving a connection, sends some dummy data
back to the calling client.
<HR>
<BLOCKQUOTE>
<B>Listing 28.4. Connection-oriented server using Perl.<BR>
</B>
</BLOCKQUOTE>
<BLOCKQUOTE>
<TT><FONT FACE="Courier"> 1 #!/usr/bin/perl<BR>
2 # ----------------------------------------------------------
<BR>
3 # Sample connection oriented server using Perl<BR>
4 # ----------------------------------------------------------
<BR>
5 #<BR>
6 $AF_UNIX = 1;<BR>
7 $AF_INET=2; # Use AF_INET
and not AF_UNIX.<BR>
8 $SOCK_STR = 1; # Use STREAMS.<BR>
9 $PROTOCOL = 0; # stick to the default protocols
(IP).<BR>
10<BR>
11 $SIG{'KILL'} = cleanup;<BR>
12 $SIG{'INT'} = cleanup;<BR>
13 $port = 6783 unless $port;<BR>
14<BR>
15 #<BR>
16 # The pattern for packing into a sockaddr structure<BR>
17 #<BR>
18 $PACKIT='S n C4 x8';<BR>
19<BR>
20 #<BR>
21 # Disable any buffering on any newly created sockets.<BR>
22 #<BR>
23 select(NEWSOCKET);<BR>
24 $| = 1;<BR>
25 select(STDOUT);<BR>
26<BR>
27 #<BR>
28 # Create the socket.<BR>
29 #<BR>
30 socket(MY_SOCKET, $AF_INET, $SOCK_STR, $PROTOCOL) ||<BR>
31 die
"\n $0: Cannot open socket: $!";<BR>
32 print "Socket successfully opened\n";<BR>
33<BR>
34 #<BR>
35 # Get the host address for this node<BR>
36 #<BR>
37 ($name, $aliases, $addrtype, $len, @addrs) = gethostbyname("ikra.com");
<BR>
38 ($a,$b,$c,$d) = unpack('C4',$addrs[0]);<BR>
39 print "Server Name=$name, Server Address= $a.$b.$c.$d\n";
<BR>
40 $my_ip_addr = pack($PACKIT,$AF_INET,$port,$addrs[0]);<BR>
41<BR>
42 #<BR>
43 # Bind to the socket and listen on this port<BR>
44 #<BR>
45<BR>
46 bind(MY_SOCKET, $my_ip_addr) || die "$0: Cannot bind ..
$!\n";<BR>
47<BR>
48 print "\n Bound to socket";<BR>
49 listen(MY_SOCKET,5) || die "$0: Cannot listen:
$!\n";<BR>
50 print "\n Listening \n";<BR>
51<BR>
52 $remote = accept(NEWSOCKET, MY_SOCKET)
|| die "$0: Unacceptable: $!\n";<BR>
53 #<BR>
54 # In case you have to display incoming connection<BR>
55 # information, you can uncomment the next three lines of code:
<BR>
56<BR>
57 @remoteInfo
= unpack($PACKIT,$remote);<BR>
58 $, = '
';<BR>
59 print
@remoteInfo; print " <<- Remote \n";<BR>
60<BR>
61 close MY_SOCKET;<BR>
62 select(NEWSOCKET);<BR>
63 $| = 1;<BR>
64 print NEWSOCKET "Kamran was
here\n";<BR>
65 print NEWSOCKET "Another
line\n";<BR>
66 $i = 0;<BR>
67 srand();<BR>
68 while(1){<BR>
69 $tick
= rand() * 100;<BR>
70<BR>
71<BR>
72 printf
" $i: %6.2f \n", $tick;<BR>
73 $i++;
<BR>
74 if ($i
> 1000)<BR>
75 {
<BR>
76 close
NEWSOCKET;<BR>
77 exit(0);
<BR>
78 }
<BR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -