CodeEatingMyMind
CodeEatingMyMind

Reputation: 7

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();

Upvotes: 0

Views: 2791

Answers (3)

Razor
Razor

Reputation: 2641

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.

Upvotes: 0

AJ.
AJ.

Reputation: 4534

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.

Upvotes: 1

Paul Lammertsma
Paul Lammertsma

Reputation: 38252

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.

Upvotes: 1

Related Questions