I tried to extend Socket object something as…
public class TestSocket extends Socket
{
private String id=String.valueOf(Math.random());
...
public void setId(String id){this.id=id;}
public String getId(){return this.id;}
}
init as…
TestSocket testSocket = new TestSocket(SERVER_HOSTNAME, SERVER_PORT);
As I can see it, the server side ServerSocket standard code like a
TestSocket mySocket = (TestSocket) serverSocket.accept();
… according to docs accept() method re-inits socket object and returns a new one so the id value is not the client’s one but a regenerated one 🙁
Is it possible to keep a client id? If yes then how?
I presume the line
would raise a
ClassCastExceptionsincejava.io.ServerSocket.accept()returns an instance of classSocket, notTestSocket(unless you inherited from ServerSocket).You probably have to send the ID over the connection and set it on the receiving end if you want to connect the two sockets, like:
One of your two test sockets would call the one method and the other the other.
I would not, however, inherit from the Socket classes to perform this, but handle this on a higher level.