简体   繁体   中英

Socket and Thread, what does this code do?

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 ?

}

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM