0

Struggling with what is probably simple syntax to 'retrieve' a reference to a socket which is already connected so I can 'reuse' it.

This code works fine (the socket stays open once created)-

String thisIP = var4.getString("ipaddress"); 

try {
    if ((this.socket == null || !this.socket.isConnected()) && this.running == 0) {
        this.running = 1;         
        socket = new Socket(thisIP, 2001);
    } 

In a separate java class / file I need to 'retrieve' and reuse the socket, so something like -

queryStatus of the socket connected to "192.168.150.210" and return the entire socket reference (IP address, port number and locally bound IP port) so I can reuse it in a PrintWriter statement

new PrintWriter(s.getOutoutStream()) 

where s is the socket reference

I assume I require some sort of array to store all the previously created socket references?

I cant just create a new socket and use that because the third party IP device (a LAN module) only allows 1 TCP client connection.

Thoughts appreciated. Regards Ralph

deHaar
  • 17,687
  • 10
  • 38
  • 51
Ralph
  • 115
  • 1
  • 13
  • 1
    Hmm, your question seems a bit unclear. "Reuse" in terms of socket usually means using it for **another** connection after it has been used. You seem to want to *retrieve* the reference to the socket somewhere else in the code, right? – Florian Albrecht Oct 22 '18 at 09:25
  • Yes, retrieve the socket reference in another class (I know the IP address and have to retrieve the socket to that IP address so I can send data to it). – Ralph Oct 22 '18 at 09:37
  • @Ralph Then your solution is a getter for socket. – jokster Oct 22 '18 at 09:41
  • Thanks, please elaborate, socket.getIP(ipaddress) or similar doesn't seem to work – Ralph Oct 22 '18 at 09:56
  • Possible duplicate of [Finding out what network sockets are open in the current Java VM](https://stackoverflow.com/questions/11669554/finding-out-what-network-sockets-are-open-in-the-current-java-vm) – Florian Albrecht Oct 22 '18 at 10:38
  • Additionally to the referenced duplicate question, your specific problem seems to boil down to "how do I store a reference in Java and access it later on?". That's a pretty basic, socket-unspecific problem. – Florian Albrecht Oct 22 '18 at 10:41
  • Thanks, I know how to store a reference and the 'duplicate' suggestion is of no use because that can only run once (I have to run multiple times). I was rather hoping there would be a socket method that allowed me to retrieve the complete socket, obviously not. – Ralph Oct 22 '18 at 11:02
  • Yeah, but exactly that information (there is no such method) is also given in the duplicate, so that flag may very well be valid... – Florian Albrecht Oct 22 '18 at 15:42

0 Answers0