作为记录,我相信您的特殊情况最好通过组合而不是继承来解决。Aka,最好包装通过检索的套接字accept
,而不是像现在一样尝试子类化。有一本好书(Joshua Bloch 的 Effective Java)描述了何时使用组合而不是继承。阅读后,如果您认为继承适合您的用例,您可以为套接字实现它,如下所示:
更专业的套接字实现:
public class AuditableClientSocket extends Socket {
private long lastPacketReceived = -1;
// Constructors removed for brevity. Add them back here
public long getLastPacketReceived() {
return lastPacketReceived;
}
protected void setLastPacketReceived(long lastPacketReceived) {
this.lastPacketReceived = lastPacketReceived;
}
public String formatLastReceived() {
if (lastPacketReceived < 0)
return "Never";
return new Date(lastPacketReceived).toString();
}
}
能够创建专用套接字的服务器套接字实现:
public class AuditableClientServerSocket extends ServerSocket {
// Constructors removed for brevity. Add them back here
@Override
public Socket accept() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!isBound())
throw new SocketException("Socket is not bound yet");
final Socket s = new AuditableClientSocket((SocketImpl) null);
implAccept(s);
return s;
}
}
测试类:
public class AuditableClientServer implements Runnable {
public static void main(String[] args) {
AuditableClientServer server = new AuditableClientServer();
new Thread(server).start();
}
private AuditableClientServerSocket serverSocket = null;
public void run() {
try {
serverSocket = new AuditableClientServerSocket(5656);
final AuditableClientSocket sock = (AuditableClientSocket) serverSocket.accept();
System.out.printf(
"Client connected at %s. Last received packet at %s",
new Date(), sock.formatLastReceived());
sock.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class AuditableClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 5656);
s.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}