Java Socket Programming (III) Server Sockets_java programming

Source: Internet
Author: User
Article Source: ASPCN Author: Sun Wen

Server sockets

Listing 9.2 is part of a server application.

List 9.2 A simple server program

/**
* A program that listens on ports and provides HTML documents.
*/
Class Simplewebserver {
public static void Main (String args[])
{
ServerSocket serversocket = null;
Socket clientsocket = null;
int connects = 0;
Try
{
{
Set up a server socket
ServerSocket = new ServerSocket (80, 5);
while (connects < 5)
{
Waiting 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
{
Get IO Stream
inbound = new DataInputStream (Client.getinputstream ());
Outbound = new DataOutputStream (Client.getoutputstream ());
Formatted output (response headers and very few HTML documents)
StringBuffer buffer = Prepareoutput ();
String Inputline;
while ((Inputline = Inbound.readline ())!= null)
{
If you are at the end of the HTTP request, send a response
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 is not actively establishing a connection. Instead, they are passively listening to a client's connection for instructions and then serving them. The server is created by the class ServerSocket. The following program establishes a server-side socket and binds it to port 80:

ServerSocket serversocket = new ServerSocket (80, 5);

The first parameter is the port on which the server listens. The second parameter is optional. This is a listening time in the API documentation, but the second parameter in the traditional socket program is the listening depth. A server can receive multiple connection requests at the same time. But only one at a time. The listening heap is an unanswered connection request queue. The above request establishes a connection to handle the last five requests. If one of the following arguments is omitted, the default value is 50.

ServerSocket serversocket = new ServerSocket (80, 5);

Once the socket is established and a listening connection is started, incoming connections are established and placed in the listening heap. The ACCETP () method removes the connection in the heap.

Socket clientsocket = serversocket.accept ();

This method returns a client connection that is used to talk to a visitor. The server itself is unlikely to establish a conversation, instead, the server socket uses the Accept () method to generate a new socket. The server socket still opens and arranges new connection requests.

As with the client socket, the following step establishes the input and output streams:

DataInputStream inbound = new DataInputStream (Clientsocket.getinputstream ()); DataOutputStream outbound = new DataOutputStream (Clientsocket.getoutputstream ());

General I/O operations can be used in a new stream. It waits for the client to send a blank line before the server responds. When the session ends, the server closes the stream and the client socket. What happens if you don't ask for instructions in the queue? That method will wait for one to come. This behavior is called blocking. The Accept () method blocks the server thread until a call arrives. The server exits after 5 connections have been processed. Any calls in the queue will be canceled.

All servers should have the following basic steps:

1. Set up a server socket and start listening.

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

3. Establish input and output streams.

4. Generate a session on an existing protocol.

5. Close the client stream and socket.

6. Go back to step two or step seventh.

7. Shut down the 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.