Using the Socket class in Java, I’m trying to create a network of six clients that are each connected to each other.
I’ve got decent idea in place so far, I think, I’m just not sure how to do this.
Basically, I’ve got a list of hostnames stored in a String array. I open a ssh connection to each of the machines that I’ll be using, and launch my clients one by one.
The first client finds its hostname with InetAddress.getLocalHost().getHostName(), then compares this to the hostname list and figures out its NodeID:
for(i = 0; i < hostNames.length; i++){
if(localHostName == hostNames[i]){
NodeID = i;
break;
}
...
So here’s the hard part for me: I would at this point connect to the client at hostNames[i]. My plan was to have a different thread for each connection for each client. How should I go about creating these threads? Should I have a thread array set up beforehand and define the threads at this point?
Thread[] connections = new Thread[]();
...
//in for loop
connections[i] = new Thread(new ConnectionThread().start(hostNames[i]));
// ConnectionThread being a tentative name for a custom class
This seems like it would be simple enough, but am I overthinking it? Oversimplifying it?
Right away you’ve committed a newbie blunder:
will always be
false, because in java the==operator compares object identity – ie are the two objects the same object. What you want is:Next, the
Thread[]idea is good, but pass in aRunnableto the thread and start the thread. Have your class use an instance field for the hostnames to connect to (the class doesn’t need to know its own hostname).Something like this:
Then in your main (simplistically):