Build your own QQ using Java (3)

Source: Internet
Author: User
Serversocket class

Because ssclient uses a stream socket, the service program must also use a stream socket. This requires creating a serversocket object. serversocket has several constructor functions. The simplest is serversocket (INT port). When serversocket (INT port) is used to create a serversocket object, the port parameter transmits the port number, this port is the port on which the server listens for connection requests. If an error occurs at this time, an ioexception object will be thrown. Otherwise, a serversocket object will be created and ready to receive connection requests.

Next, the service program enters an infinite loop. The infinite loop starts from the call of the serversocket accept () method. After the call starts, the accept () method will cause the call thread to block until the connection is established. After the connection is established, accept () returns a newly created socket object bound to the IP address or port number of the client program.

Because a single service program may communicate with Multiple customer programs, it cannot take much time for the service program to respond to the customer program, otherwise, the customer program may spend a lot of time waiting for the establishment of communication before obtaining the service. However, the session between the service program and the customer program may be long (similar to the phone number ), therefore, to speed up the response to the client program connection request, a typical method is to run a background thread on the server host, which processes the communication between the service program and the client program.

To demonstrate the concepts we mentioned above and complete the ssclient program, we will create an ssserver program. The program will create a serversocket object to listen to connection requests on port 10000, if the connection is successful, the service program waits for the connection input, starts a thread to process the connection, and responds to commands from the client program. The code for this program is as follows:

Listing 3: ssserver. Java


// Ssserver. Java

Import java. Io .*;
Import java.net .*;
Import java. util .*;

Class ssserver
{
Public static void main (string [] ARGs) throws ioexception
{
System. Out. println ("server starting.../N ");

// Create a server socket that listens for incoming connection
// Requests 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 that 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 read from the socket to characters.
// 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
// Intermediate output stream writer that converts
// Characters sent to the socket to bytes. The conversion
// Is based on 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,
// 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 has closed its output stream.

If (cmd = NULL)
Break;
  
// Convert command to uppercase, for example, of comparison.

Cmd = cmd. touppercase ();

// If client program sends bye command, terminate.

If (CMD. startswith ("bye "))
Break;

// If client program sends date or time command, return
// Current date/time to the client program.

If (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 (as a string) to the client
// Program.

If (CMD. startswith ("Dow "))
Switch (C. Get (calendar. day_of_week ))
{
Case calendar. Sunday: pw. println ("Sunday ");
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 (true );
{
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)
{
}
}
}
}

Run this program to get the following output:

Server starting...
Accepting connection...
Closing connection...

The source code of ssserver declares a pair of classes: ssserver and serverthread; the main () method of ssserver creates a serversocket object to listen to connection requests on port 10000. If yes, the ssserver enters an infinite loop and calls the serversocket accept () method to wait for the connection request, and starts the background thread to process the request returned by the connection (accept ). The thread starts from the start () method inherited by serverthread and runs the code in the run () method of serverthread.

Once the run () method runs, the thread creates bufferedreader, printwriter, and calendar objects and enters a loop, which is read by the read (through the Read line () of bufferedreader ()) A line of text from the client program starts. The text (command) is stored in the string object referenced by CMD. What happens if the client program closes the output stream too early? The answer is: cmd will not be assigned a value.

Note that this situation must be taken into account: when the service program is reading the input stream, the client program closes the output stream. If this situation is not processed, the program will generate an exception.

Once the source code of ssserver is compiled, you can enter Java ssserver to run the program. After running ssserver, you can run one or more ssclient programs.

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.