In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use the ServerSocket class of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the ServerSocket class of Java.
ServerSocket class
Because SSClient uses stream sockets, service programs also use stream sockets. This is to create a ServerSocket object. ServerSocket has several constructors, the simplest is ServerSocket (int port). When you use ServerSocket (int port) to create a ServerSocket object, the port parameter passes the port number, which is the port on which the server listens for connection requests. If an error occurs at this time, an IOException exception object will be thrown, otherwise the ServerSocket object will be created and ready to receive connection requests.
The service program then enters an infinite loop, which starts with a call to ServerSocket's accept () method, which causes the calling thread to block until the connection is established after the call starts. After establishing the connection, accept () returns a recently created Socket object that is bound to the client's IP address or port number.
Because of the possibility of a single service program communicating with multiple client programs, it should not take much time for the service program to respond to the client program, otherwise the client program may spend a lot of time waiting for the communication to be established before it is serviced. However, the conversation between the service program and the client program may be very long (similar to the telephone), so in order to speed up the response to the client connection request A typical method is for the server host to run a background thread that handles the communication between the service program and the client program.
To demonstrate the idea we talked about above and complete the SSClient program, let's create a SSServer program that will create a ServerSocket object to listen for connection requests on port 10000. If successful, the service program will wait for the connection input, start a thread to process the connection, and respond to commands from the client program. Here is the code for this program:
Listing 3: SSServer.JavaXML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" / >
/ / 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. 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 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, 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 has closed its output stream.
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
/ / 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)
{
}
}
}
}
Running this program will get the following output:
Server starting...
Accepting Connection...
Closing Connection...
The source code of SSServer declares a pair of classes: the main () method of SSServer and ServerThread;SSServer creates a ServerSocket object to listen for connection requests on port 10000. If successful, SSServer enters an infinite loop, alternately calling the accept () method of ServerSocket to wait for the connection request, while starting the background thread to process the request returned by the connection (accept ()). The thread starts with the start () method inherited by ServerThread and executes 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 that starts by reading (through BufferedReader's readLine ()) a line of text from the client program, which is stored in the string object referenced by cmd. What happens if the client program closes the output stream prematurely? The answer is: cmd will not be assigned.
Note that it is important to take into account the situation in which the client closes the output stream while the server is reading the input stream, and if this situation is not handled, the program will generate an exception.
Once the source code for SSServer is compiled, run the program by typing Java SSServer, and after you start running SSServer, you can run one or more SSClient programs.
At this point, I believe you have a deeper understanding of "how to use the ServerSocket class of Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.