Java Socket programming (3) server Sockets

Source: Internet
Author: User

Source: aspcn Author: Sun Wen

Server Sockets

List 9.2 is part of a server application.

List 9.2 a simple server program

/**
* A program that listens to the port and provides HTML documents.
*/
Class SimpleWebServer {
Public static void main (String args [])
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
Int connects = 0;
Try
{
{
// Create a server socket
ServerSocket = new ServerSocket (80, 5 );
While (connects
{
// Wait for connection
ClientSocket = serverSocket. accept ();
// Service connection
ServiceClient (clientSocket );
Connects ++;
}
ServerSocket. close ();
}
Catch (IOException ioe)
{
System. out. println ("Error in SimpleWebServer:" + ioe );
}
}
Public static void ServiceClient (Socket client)
Throws IOException
{
DataInputStream inbound = null;
DataOutputStream outbound = null;
Try
{
// Obtain the IO stream
Inbound = new DataInputStream (client. getInputStream ());
Outbound = new DataOutputStream (client. getOutputStream ());
// Format the output (response header and few HTML documents)
StringBuffer buffer = PrepareOutput ();
String inputLine;
While (inputLine = inbound. readLine ())! = Null)
{
// If the HTTP request is reached, a response is sent.
If (inputLine. equals (""))
{
Outbound. writeBytes (buffer. toString ());
Break;
}
}
}
Finally
{
// Clear
System. out. println ("Cleaning up connection:" + client );
Tln ("Cleaning up connection:" + client );
Outbound. close ();
Inbound. close ();
Client. close ();
Client. close ();
}
}
The server does not actively establish a connection. on the contrary, they passively listen to a client connection request and then serve them. the server is created by the ServerSocket class. the following program creates a server socket and binds it to port 80:

ServerSocket serverSocket = new ServerSocket (80, 5 );

The first parameter is the port to be listened to by the server. the second parameter is optional. the API documentation shows that this is a listener time, but in traditional socket programs, the second parameter is the listener depth. A server can receive multiple connection requests at the same time, but only one connection request can be processed at a time. the listener heap is an unanswered connection request queue. the preceding request establishes a connection to process the last five requests. if the following parameter is omitted, the default value is 50.

ServerSocket serverSocket = new ServerSocket (80, 5 );

Once the socket establishes and starts listening for the connection, the incoming connection will be established and placed in the listener heap. accetp () method to retrieve the connection in the heap.

Socket clientSocket = serverSocket. accept ();

This method returns a client connection used to talk to the visitor. the server itself cannot establish a conversation. On the contrary, the server socket will use the accept () method to generate a new socket. the server socket still opens and lists new connection requests.

Like the client socket, the following step creates an input and output stream:

DataInputStream inbound = new DataInputStream (clientSocket. getInputStream (); DataOutputStream outbound = new DataOutputStream (clientSocket. getOutputStream ());

General I/O operations can be used in the new stream. before the server responds, it waits for the client to send a blank line. when the session ends, the server closes the stream and client socket. what will happen if there is no request in the queue? That method will wait for a while. this action is called blocking. the accept () method will block the server thread until a call arrives. after the five connections are closed, the server exits. any call in the queue will be canceled.

All servers have the following basic steps:

1. Create a server socket and start listening.

2. Use the accept () method to obtain a new connection.

3. Create input and output streams.

4. Generate a session on an existing protocol.

5. Disable the client stream and socket.

6. Go back to step 2 or step 7.

7. Disable server socket.

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.