Reputation: 526
I found an exercice (it's not homework or anything, no worries) : comment the following code. The problem is, i don't know what this code do. I put my comment so far. Is that correct ?
public class A {
private ServerSocket a;
// constructor
public A (int p) {
a = new ServerSocket(p); // create a server socket on port p.
while(true) { // infinite loop
Socket c = a.accept(); // accept the connection from the client.
Thread th = new Thread(new B(c)); // huh... wtf ? Is that a thread declaration with the
//runnable interface ?
//I have no idea. c socket is copied
// in B class field by B constructor.
}
}
public class B implements Runnable {
private Socket a;
// constructor
public B(Socket aa) {
a = aa; // copying a socket.
}
public void run() { // overide run methode from runnable ? I don't remember, there is a thing with run...
/// Question from the exercice : what should i put here ?
}
}
Upvotes: 0
Views: 45
Reputation: 2863
Assuming you already know what a thread is. The code listens for incomming connections inside the while loop. Then accepts a connection and creates a new thread with an instance of B
. The thread then will call the run
method of this object (of the B object)
To answer the question of the exercise: You could put a send or receive logic in the run method.
Note: You need to call
th.start();
of the newly created thread object in order to make the thread execute the run method.
Also the socket is not copied to the B object, but a reference is passed. So both variabled hold the same object.
Upvotes: 1