The relationship between Servlet and Applet is generally indirect, that is, the page request is sent to the Servlet by the browser. As a response, the Servlet sends the HTML document generated by the result to the browser. In many cases, it is unnecessary to establish a direct connection between Servlet and Applet. However, if you want to display real-time dynamic data, such as chat room windows, news displays, and stock market quotations, it is useful to establish a direct connection between the two. In particular, such communication is essential in more complex distributed Java applications. This complex interaction method between the client Java program and the Server Java program is not enough to use Servlet and Applet APIs. This article introduces and compares four communication methods: passing parameters through the HTML page, using the network functions of the java.net package to establish a direct network connection, remote method call RMI) and CORBA.
1. Passing Applet parameters through HTML pages
Passing parameters through HTML pages is the most common method to establish a connection between Servlet and Applet. Servlet only needs to write the parameters passed to the Applet into the HTML page. This type of communication is unidirectional and is used to implement Servlet control over the Applet.
2. Use the java.net package to establish two-way communication
The second method is to use the network capabilities provided by the java.net package. Taking the connected stream communication method as an example, the operations on the server side are generally:
Create a ServerSocket object to listen to requests sent from the client on the specified port. When a request is received, the accept () method returns a Socket object.
Use the preceding Socket object to create input and output stream objects. Interacts with customers through input and output streams. After the interaction is complete, close the input and output streams and Socket. When the service program ends, disable ServerSocket. The implementation code class is as follows:
- Try {
- BooleanFlag=True;
- SocketClientSocket=Null;
- ServerSocketServerSocket=NewServerSocket (0 );
- System. out. println ("Server listen on:" + serverSocket. getLocalPort ());
- While (flag ){
- ClientSocket=ServerSocket. Accept ();
- DataInputStreamIs=NewDataInputStream (new bufferedInputStream (clientSocket
- . GetInputStream ()));
- PrintStreamOS=NewPrintStream (new bufferedOutputStream (clientSocket. getOut
- PutStream ()));
- // Process the Applet request
- OS. close ();
- Is. close ();
- ClientSocket. close ();
- }
- ServerSocket. close ();
- } Catch (IOException e ){
- System. err. println ("Exception:" + e );
- }
- Analysis of Servlet Web Applications
- Install Servlets and JSP
- Running Environment of Servlets and JSP-JRun
- Getting started with the Servlets Engine
- Introduction to Java Servlets and CGI programs