Java applications in the Client/Server network

Source: Internet
Author: User

Java applications in the Client/Server network

Rizhao Port Authority-Liu Yang

---- With the Java language's daily beneficial stream, it is specially the combination of Java and Internet Web, which makes it a huge success in the whole ball. Java language is uniquely positioned on the platform, face-to-face, distributed, multiline cable, and well-developed security host system, it is a good development platform and Transportation Environment in the current information generation system.

I. Java Network Model

---- Similar to the multi-environment on the Internet, the entire Java environment should also be a customer machine/server environment, more accurately, it is the Browser/Server model (Web model ). However, it is different from the two-layer structure of the data transfer Client/Server (C/S, the Web Model of Java should be composed of three layers. The C/S structure of the data transmission system is based on the message transmission mechanism. The client sends the data to the server, after the server goes into the corresponding processing, it is delivered to the customer's end through the delivery machine. In the Web model, the server is divided into two parts: the server is used (Web Server ), the other part is the data warehouse server.

Java Network Application Model

---- For the distributed computing environment, Java provides good support through its network class library. For data distribution, Java provides a URL (Uniform Resource Locator) object. This object can be used to open and access the object on the network, the access method is almost the same as the access local file system. Deploy operations, java client/server models can be used to separate the computing workload from the server to the client (the server is responsible for providing query results, customer machine is responsible for organizing the results of the display), and increases the overall delivery efficiency of the entire system, increasing dynamic scalability. Java Network Class Library is an extension of Java language to adapt to the Internet environment. In addition, in order to adapt to the uninterrupted development of the Internet, Java also provides dynamic expansion suggestions, so that the Java Network Class Library can be expanded without interruption.

---- Java Network Library supports multiple Internet protocols, including telnet, FTP, and HTTP (WWW ), the corresponding sub-class library of the Java Network Class Library is:

Java.netJava.net.ftpJava.net.www.contentJava.net.www.htmlJava.net.www.http

---- These sub-classes each have their own class and method that can be used to handle Internet negotiations. Among them, java.net is used to handle some basic network functions, including remote login (Telnet) and java.net. FTP is used for handling FTP; java.net. www. content is used for processing the content on the WWW page, including java.net.www.html and java.net. www. HTTP provides support for HTML language and HTTP protocol.

Ii. Java applications in the environment of customer machines/Server

---- The customer machine/server uses the network communication mode based on the connection in the distributed processing process. The communication model first defines a communication agreement between the client and the server, and creates a socket class, use this class to establish a reliable link. Then, the customer machine/server can transmit data through the chain. The customer server sends the request, and the server supervisor listens to the request from the customer server, and provides the customer server with the response service. This is a typical "please? -- Answer: "mode. What is the customer below? /A typical task of the server:

---- 2. Import of the server listener's corresponding ports;

---- 3 * send a request from the client;

---- 5. The server receives this request;

---- 6. The server handles this request and returns the result to the client;

---- 7. Repeat the preceding process until it is completed into a session.

---- According to the preceding process, we use Java language to compile an application for the server and the client ). When the process is on the server, the process is responsible for monitoring the customer's machine, please request, for each customer's machine, please create a socket connection, provide services for the customer. The service provided in this process is: Read a line of text from the user's machine, reverse the text, and send it back to the user's machine.

---- We can see through this example that when we use Java to set the C/S process order, we need to note the following points:

---- (1) the server shall use the ServerSocket class to handle the connection of the customer's host. When the client is connected to the client port monitored by the server, ServerSocket will be allocated with a new Socket image. This new Socket pair connects to some new ports, and is responsible for communicating with the customer's host. Then, the server continued to listen to the ServerSocket to handle new client connections.

---- Socket and ServerSocket are two types provided by Java Network Class Libraries.

---- (2) the server uses a multi-line machine. Server is a thread, and its run () method is a non-restricted cycle. It uses monitoring to connect the customer's host. Each time a new client is connected, ServerSocket creates a new Socket instance, at the same time, the server will also create a new line, that is, a Connection object, based on Socket communication. All communications with the client are handled by the Connection. The number of constructor functions of Connection is initially based on the Socket-to-image communication stream, and starts the operation of the dynamic line. Communication with the customer's host and service provision are handled by Connection.

---- (3) create a Socket pair for the customer first, and use it to communicate with the server. After that, you need to create two pairs: DataInputStream and PrintStream. The former uses the InputStream of the Socket to input data into the stream to read data, the latter is used to write data to the Socket OutputStream. Finally, the customer's machine sequence reads data from the quasi-input (for example, the console) and writes the data to the server, when the server reads the expected answer information, the answer information is later written to quasi-output.

---- Clear the order in the source sequence of the server and the client. In this tutorial, JDK1.1 has been used in the network environment (TCP/IP) of NT 4.0.

---- 2. Compile and write Server Java program

// Server. javaimport java. io. *; import java.net. *; public class Server extends Thread {public final static int Default_Port = 6543; protectd int port; protectd ServerSockrt listen_socket; // Fixed Output Error example: if the output result is abnormal or incorrect, return the process order.
Public static void fail (Exception e, String msg) {System. err. println (msg + ":" + e); System. exit (1);} // determine and enable the Socket process of the server. Please contact the monitoring host. Public Server (int port) {if (port = 0) port = Default_Port; this. port = port; try {listen_socket = new ServerSocket (port);} catch (IOException e) fail (e, "Exception creating server socket"); System. out. println ("Server: listening on port" + port); This. start ();}

----/* The following is the main process sequence of the listener route of the server. This line goes through the loop directly. Please listen and receive the connection from the client. For each connection, a connection object is generated, and a message is sent through the Socket channel.

*/Public void run () {try {while (true) {Socket client_socket = listen_socket.accept (); Connection c = new Connection (client_socket) ;}} catch (IOException e) fail (e, "Exception while listening for connections")} // public static void main (String args []) {int port = 0; if (args. length = 1) {try port = Integer. parseInt (args [0]); catch (NumberFormatException e) port = 0;} new Server (port);} // End The main} // End of Server class // defines the Connection class, which is a line used to handle communication with the customer. Class Connection extends Thread {protected Socket client; protected DataInputStream in; protected PrintStream out; // The initial communication flow and startup of the public Connection (Socket client_socket) {client = client_socket; try {in = new DataInputStream (client. getinputStream (); out = new PrintStream (client. getOutputStream ();} catch (IOException e) {try client. close (); catch (IOException e2); System. err. println ("Exception while ge Using socket streram: "+ e); Return;} this. start;} // End of Connection method // server example: Read a line of text; reverse conversion; return to text. Public void run () {String line; StringBuffer revline; int len; try {for (;) {// Read a lineline = in. readline (); if (line = null) break; // Reverse the linelen = line. length (); revline = new StringBuffer (len); for (int I = len-1; I> = 0; I --) revline. insert (len-1-I; line. charAt (I); // Write out the reverse lineout. println (revline);} catch (IOException e); finally try client. close (); catch (IOException e2);} // End Run method} // End of Connection class3 * compile and write the Java program of the customer machine class // Client. javaimportjava. io. *; importjava.net. *; public class Client extends {public static final int Default_Port = 6543; // fixed output example public static final void usage () {System. out. println ("Usage: Java Client <> [<>]"); System. exit (0);} public static void main (String args []) {int port = Default_Port; Socket s = null; // parse the parameter if (args. length! = 1) & (args. length! = 2) usage (); if (args. length = 1) port = Default_Port; else {try port = Integer. parseInt (args [1]); catch (NumberFormaatException e) usage ();} try {// generate a Socket, communicates with the host through the specified port. S = new Socket (args [0], port); // The text character stream DataInputStream sin = new DataInputStream (s. getInputStream (); PrintStream sout = new DataInputStream (s. getInputStream (); // read the character stream DataInputStream in = new DataInputStream (System. in); // return the address of the connection and the end port System. out. println ("Connected to" + s. getInetAddress () + ":" + s. getPort (); String line; For (;) {// The explicit identifier System. out. print (">" ); System. out. flush (); // line = in. readline (); if (line = null) break; // send the received text line to the server sout. println (line); // receives a line of line = sin from the server. readline (); // Check if connection is closed (I. e. for EOF) if (line = null) {System. out. println ("Connection closed by server. "); Break;} // displays the received character System on the console. out. println (line);} // End of for loop} // End of trycatch (iow.t Ion e) System. err. println (e); // Always be sure to close the socketfinally {try if (s! = Null) s. close (); catch (IOException e2) ;}// End of main} // End of Client

---- The first parameter must be taken as the server master machine name when the customer's route is run, the server port number is the second parameter, in which the server port number can be omitted.

----Mailing address:
276826
Huanghai Road, Rizhao City, Shandong Province
According to the Hong Kong affairs bureau's information center
Liu Yang
Tel: 0633-8382561
Mailto: liuyang98@163.net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.