简体   繁体   中英

ServerSocket accept method - How can I down cast to a subclass type?

I have a class ClientSocket that extends class Socket. The reason I extend class Socket, is that I want to include a String clientId that uniquely identifies a client on the other side of the socket. I also have a method called 'getClientId' that returns the clientId.

I have a ServerSocket instance running on my server that accepts socket connections like so:

public Socket acceptNextConnection() throws IOException {
    Socket socket = serverSocket.accept();

    // put the client socket into the map
    ClientSocket clientSocket = (ClientSocket) socket;
    clientConnections.put(clientSocket.getClientId(), clientSocket);

    return clientSocket;
}

As you can see, my cast here is incorrect as a Socket instance IS NOT a ClientSocket instance and so I get a class cast exception, as I expected. As is evident in the code, I want to call 'getClientId' on class ClientSocket. However I can't do this because the serverSocket.accept method returns a Socket object at runtime, not a ClientSocket. My question is, is there a way around this? If not, is there a neater way of doing what I want, which is being able to uniquely identify a socket that is bound to a client? An ip address can be subject to change.

Thanks for the help.

You can have a ServerClientSocket which return a ClientSocket from accept. Something like

public class ServerClientSocket extends ServerSocket {
  public ClientSocket accept() throws IOException {
  if (isClosed())
    throw new SocketException("Socket is closed");
  if (!isBound())
    throw new SocketException("Socket is not bound yet");
  ClientSocket s = new ClientSocket((SocketImpl) null);
  implAccept(s);
  return s;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM