简体   繁体   中英

Threads and Handlers in server socket

How is the new Handler(clientSocket); instantiated without an object?. Can somebody give some insight?

public class Server1 {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(15897);
            while (true) {
                Socket clientSocket = serverSocket.accept();

                new Handler(clientSocket);

            }
        } catch (IOException e)
        {
            System.out.println("problem here 1");
        }
    }
}

class Handler implements Runnable {

    int red;
    int reads, r;

    Socket clientSocket;

    Handler(Socket s)
    {
        this.clientSocket = s;

        new Thread(this).start();

    }

    public void run(){        
        BufferedReader bufferedReader;
        try {

            bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String inputLine = bufferedReader.readLine();

Your code is incomplete, so it's difficult to say with certainty, but observe that in the Handler's constructor a thread is created and started, which executes run() .

Inside that function (and therefore in a separate thread), the input stream is read from the socket into a BufferedReader, from which the first line is obtained.

The thread will block until a line is received over the socket connection.

Because your code is cut off from that point, I can't say what else it does.

In you code Server is made to keep listening the incoming Clients.

       Socket clientSocket = serverSocket.accept();

serverSocket.accept() waits until a connection or a client is found. If client is found then accept() function returns a local socket which is connected to another socket at the client which is given to clientSocket in you code.

new Handler(clientSocket);

Now clientSocket is given to Handler class in which you are using thread for reading the data given by that clientSocket .

The purpose of thread here is to handle each incoming clientSocket seprately.

I am not sure what exactly does the code do but explaining it to you as per the concept of OOPs, it creates an instance of the Handler class everytime the while loop is executed.

Warning: The while(true) loop is bad code and when the project is run, it will run in an infinite loop.

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