The implAccept method of the ServerSocket class can be used to return a Socket subclass object. However, implAccept is the protected method. Therefore, you must overwrite the accept method in the subclass of the ServerSocket class, and then use the implAccept method in the accept method to reset the Socket object. The implAccept method is defined as follows:
Protected final void implAccept (Socket s) throws IOException
As long as an unconnected Socket subclass object is set through the implAccept method, the accept method returns a connected Socket subclass object (the accept returns a Socket object to retrieve the Socket subclass object, type conversion is required ). In most cases, you do not need to change the behavior of the accept method, but sometimes you need a Socket class with more features. This can be achieved through the implAccept method. The following code defines an HttpSocket class inherited from the Socket. In addition to all the features of the Socket class, this class also adds the getRequestHeaders method to return the header information of the HTTP request.
Package server;
Import java.net .*;
Import java. io .*;
Class HttpSocket extends Socket
{
Public String getRequestHeaders () throws Exception
{
InputStreamReader isr = new InputStreamReader (getInputStream ());
BufferedReader br = new BufferedReader (isr );
String s = "", result = "";
While (! (S = br. readLine (). equals (""))
Result = result + s + "";
Return result;
}
}
Class HttpServerSocket extends ServerSocket
{
Public HttpServerSocket (int port) throws IOException
{
Super (port );
}
Public Socket accept () throws IOException // override the accept Method
{
Socket s = new HttpSocket ();
ImplAccept (s); // sets the object type returned by the accept method to HttpSocket
Return s;
}
}
Public class CustomAccept
{
Public static void main (String [] args) throws Exception
{
HttpServerSocket httpServerSocket = new HttpServerSocket (1234 );
HttpSocket httpSocket = (HttpSocket) httpServerSocket. accept ();
System. out. println (httpSocket. getRequestHeaders (); // output the HTTP request header to the console
HttpServerSocket. close ();
}
}
Test
Run the following command:
Java server. CustomAccept
Enter the following Url in the address bar of IE:
Http: // localhost: 1234
Running result of CustomAccept in the console:
GET, HTTP, 1.1
Accept :*/*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;. net clr 1.1.4322;. net clr 2.0.50727; InfoPath.1; InfoPath.2)
Host: localhost: 1234
Connection: Keep-Alive
The preceding running result is the HTTP request header sent by IE to the server. The running result varies depending on the client configuration.