Use the Implaccept method of the ServerSocket class to return a socket subclass object using the Accept method. However, Implaccept is the protected method, so you must overwrite the Accept method in the subclass of the ServerSocket class, and then use the Accept method to reset the socket object in the Implaccept method. The Implaccept method is defined as follows:
Protected final void Implaccept (Socket s) throws IOException
As long as you set an disconnected socket subclass object by using the Implaccept method, the Accept method returns a socket subclass object that is already connected (accept returns the socket object, and you must type conversion to get the socket subclass object.) Most of the time you don't 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 a Httpsocket class that inherits from the socket, which, in addition to all the features of the socket class, adds a method getrequestheaders that returns the header information for 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 + "\ r \ n";
return result;
}
}
Class Httpserversocket extends ServerSocket
{
Public httpserversocket (int port) throws IOException
{
Super (port);
Public Socket Accept () throws IOException//Overwrite Accept method
{
Socket s = new Httpsocke T ();
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 h Ttpserversocket = new Httpserversocket (1234);
Httpsocket httpsocket = (httpsocket) httpserversocket.accept ();
System.out.println (Httpsocket.getrequestheaders ());//output HTTP request headers to the console
Httpserversocket.close ();
}
}
Test
Execute the following command:
Java server. Customaccept
Enter the following URL in the IE's Address bar:
http://localhost:1234
Customaccept the results of the operation 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 result above is the content of the HTTP request header that IE sends to the server. The results of this run vary according to the client configuration.