Java network programming 4

zhaozj2021-02-16  60

Serversocket class uses a stream sleeve in SSClient, so the service program also uses a stream socket. This is to create a serversocket object, serversocket has several constructor, the simplest ServerSocket (INT Port), when you create a ServerSocket object, the port parameter passes the port number, this port is the server listening connection request Port, if an error will throw an IOEXception exception object, otherwise the ServerSocket object will be created and ready to receive the connection request. Next, the service program enters an infinite loop, and the unlimited loop begins with the accept () method of calling ServerSocket, and the accept () method will cause the call to block until the connection is created. After establishing the connection, Accept () returns a recently created Socket object, the socket object binds the client's IP address or port number. Since there is a single service program with multiple client program communication, the service program responds to the client should not spend a lot of time, otherwise the client program will spend a lot of time before getting the service, but the service procedure and client program The session may be very long (this is similar to the phone), so the typical way to speed up the request for the client program, the typical method is that the server host runs a background thread, the backend threading processor and the client program. In order to demonstrate that we are talking about and complete the SSCLIENT program, let's create a SSServer program, the program will create a ServerSocket object to listen to the port 1000 connection request, if the successful service program will wait for the connection, start a thread processing connection And responsive to commands from the client. Here is the code of this program: Listing 3: SSSERVER.JAVA

// ssserver.javaimport java.io. *; Import java.net. *; Import java.util. *; Class ssserver {public static void main (string [] args) throws oews oews oewception {system.out.println ("Server Starting) ... / N "); // Create a Server Socket That Listens on Port 10000. Serversocket Server = New Serversocket (10000); While (True) {// listen for incoming connection requests from Client / / Programs, Establish a connection, and return a socket // Object this represents this connection. Socket s = server.accept (); system.out.println ("accepting connection ... / n"); // start a thread to handle the connection new ServerThread (s) .start ();.}}} class ServerThread extends Thread {private Socket s; ServerThread (Socket s) {this.s = s;} public void run () {BufferedReader br = null PrintWriter PW = null; try {// create an input stream reader That chains to the socket's // byte-oriented input stream. The Input Stream Reader // Converts Bytes Reader // Converts Bytes Reader // Converts . From the socket to characters The // conversion is based on the platform's default character // set InputStreamReader isr;. Isr = new InputStreamReader (s.getInputStream ()); // Create a buffered reader that chains to the input stream // reader The buffered reader supplies a convenient method // for reading entire lines of text br = new BufferedReader (isr);... // Create a print writer that chains to the socket's byte- // oriented output stream The print writer creates an // Intermediate Output Stream Writer That Converts // Characters Sent To The Socket To Bytes. The Conversion // Is Based The Platform's Default Character Set. Pw =

new PrintWriter (s.getOutputStream (), true); // Create a calendar that makes it possible to obtain date // and time information Calendar c = Calendar.getInstance ();. // Because the client program may send multiple commands, a // loop is required. Keep looping until the client either // explicitly requests termination by sending a command // beginning with letters BYE or implicitly requests // termination by closing its output stream. do {// Obtain the client program's next command String cmd = br.readline (); // Exit if client program. If (cmd == null) BREAK; // Convert Command To Uppercase, for Ease of Comparison. Cmd = cmd.touppercase () ; // if Client Program Sends Bye Command, Terminate. IF (cmd.startswith ("BYE")) Break; // i c c c p r (000) Date Or Time Command, Return // Current Date / Time To The Client Program ( cmd.startswith ("Date") || cmd.startswith ("Time")) PW.Println (C.gettime () .tostring ()); // if Client Program Sends Dom (day of month) Command, // Return Current Day of Month To the Client Program. IF (cmd.startswith ("DOM")) PW .println ("" C.Get (Calendar.day_of_month); // if Client Program Sends Dow (Day of Week) Command, // Return Current Weekday (A String) To The Client // Program. IF (CMD) .StartSwith ("Dow")) Switch (Cales Calendar.Sunday: PW.Println); Break; Case Calendar.monday: PW.Println ("Monday"); Break; Case Calendar.tuesday: PW.Println ("Tuesday"); Break;

Case Calendar.wednesday: PW.Println ("Wednesday"); Break; Case Calendar.thursday: PW.Println ("Thursday"); Break; Case Calendar.Friday: PW.Println ("Friday"); Break; Case Calendar . Saturday: PW.Println ("Saturday");} // if Client Program Sends Doy (Day of Year) Command, // Return Current Day of Year To The Client Program. IF (cmd.startswith ("DOY")) PW.Println ("" C.Get (Calendar.day_of_year); // if Client Program Sends Pause Command, Sleep for Three // Seconds. if (Cmd.StartSwith ("Pause")) Try {thread.sleep 3000);} catch (interruptedException e) {}} while; {catch (ioException e) {system.out.println (e.tostring ());} finally {system.out.println ("Closing Connection. ../N "); try {if (br! = null) br.close (); if (pw! = null) PW.Close (); if (s! = null) s.close ();} catch (IOEXCEPTION E) {}}}} Running this program will get the following output:

Server Starting ... Accepting Connection ... Closing Connection ...

SSSERVER's source code declares a pair of classes: SSServer and ServerThread; SSServer's main () method creates a ServerSocket object to listen to the connection request on port 1000, if successful, SSServer enters an infinite loop, alternately calling Serversocket's Accept ( The method is waiting to wait for the connection request while starting the request for the background thread process (Accept () returned). The thread starts from the START () method inherited by ServerThread, and executes the code in the RUN () method of ServerThread.

Once the run () method is running, the thread will create bufferedReader, PrintWriter, and Calendar objects and enter a loop, this loop is started by reading (by bufferedreader's readline ()) from the client, the text (command) is stored in the CMD reference In the String object, what happens if the customer program is too early to turn off the output flow? The answer is: CMD will not be assigned.

Note that this must be taken into account: When the service program is in the input stream, the client is turned off the output stream, and if this situation is not handled, the program will produce an exception. Once the SSServer source code is compiled, run the program by entering Java SSServer, and after starting SSSERVER, you can run one or more SSCLIENT programs.

转载请注明原文地址:https://www.9cbs.com/read-22602.html

New Post(0)