ServerSocket 接受方法 - 如何向下转换为子类类型?
我有一个扩展 Socket 类的 ClientSocket 类。我扩展 Socket 类的原因是我想包含一个 String clientId 来唯一标识套接字另一端的客户端。我还有一个名为“getClientId”的方法,它返回 clientId。
我的服务器上运行着一个 ServerSocket 实例,它接受套接字连接,如下所示:
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;
}
如您所见,我的转换不正确,因为 Socket 实例不是 ClientSocket 实例,因此我得到了类转换异常,正如我所期望的。从代码中可以明显看出,我想在类 ClientSocket 上调用“getClientId”。但是我不能这样做,因为 serverSocket.accept 方法在运行时返回 Socket 对象,而不是 ClientSocket。我的问题是,有办法解决这个问题吗?如果没有,是否有一种更简洁的方法来做我想要的事情,即能够唯一标识绑定到客户端的套接字? IP 地址可能会发生变化。
感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以拥有一个从接受返回 ClientSocket 的 ServerClientSocket。类似的东西
You can have a ServerClientSocket which return a ClientSocket from accept. Something like