Java Multi Threaded Server/Client Logic not working

371 views Asked by At

I am trying to create a Multithreaded server and client pair. Both of these classes are inheriting methods for writing and reading from a common class..I am not able to work these properly and am receiving a Null Pointer Exception. Here's my code:

//Common class for server and client

    package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import exception.AutoException;

public class DefaultSocketClient extends Thread {
    protected ObjectInputStream ois;
    private ObjectOutputStream oos;
    private Socket sok;

    public DefaultSocketClient(Socket sok) {
        this.sok = sok;
    }
public void run() {
    openConnection();
    handleSession();
    // closeSession();
}

/*
 * this methods opens connection
 */

public void openConnection() {
    try {
        ois = new ObjectInputStream(sok.getInputStream());
        oos = new ObjectOutputStream(sok.getOutputStream());
    } catch (IOException e) {
        try {
            throw new AutoException("OpenConnectionException");
        } catch (AutoException e1) {
            e1.printStackTrace();
        }
    }
}

public void handleSession() {
    Object input;
    try {
        while ((input = ois.readObject()) != null) {
            handleInput(input);
        }
    } catch (Exception e) {
        try {
            throw new AutoException("HandleSessionException");
        } catch (AutoException e1) {
            e1.printStackTrace();
        }
    }

}

private void handleInput(Object newInput) {
    System.out.println(newInput);

}

public void sendOutput(Object newOutput) {
    try {
        oos.writeObject(newOutput);
    } catch (IOException ioe) {
        try {
            throw new AutoException("ObjectOutputException");
        } catch (AutoException e1) {
            e1.printStackTrace();
        }
    }
}

/**
 * This method closes the Session between client and server
 */
public void closeSession() {
    try {
        ois.close();
        ois.close();
        sok.close();
    } catch (IOException e) {
        try {
            throw new AutoException("SessionCloseException");
        } catch (AutoException e1) {
            e1.printStackTrace();
        }
    }

}

}

//client

    /*
     * creating client
     */
    public AutoClientSocket() {
        try {
            clientSocket = new Socket(InetAddress.getLocalHost(),
                    DEFAULT_PORT_NO);
            readFromConsole = new BufferedReader(new InputStreamReader(
                    System.in));
        } catch (Exception e) {
            try {
                throw new AutoException("AutoServerConnectionException");
            } catch (AutoException e1) {
                e1.printStackTrace();
            }

        }
    }

    // starting the client
    public void startAutoClient() {
        try {
            defaultSocketClient = new DefaultSocketClient(clientSocket);
            defaultSocketClient.start();
            System.out.println("Client started...");
            defaultSocketClient.closeSession();

//          performOperation();
        } catch (Exception e) {
            try {
                throw new AutoException("ConnectionException");
            } catch (AutoException e1) {
                e1.printStackTrace();
            }
        }

    }


    public void performOperation() {
        // methods for client operations.

    }

}

//server

public class AutoServerSocket {

private int DEFAULT_PORT_NO = 7900;
private static ServerSocket autoServer;
ObjectOutputStream oos;
ObjectInputStream ois;

private DefaultSocketClient defaultSocketClient;
BuildAuto build = new BuildAuto();
FileIO io = new FileIO();

// creating server
public AutoServerSocket() {
    try {
        autoServer = new ServerSocket(DEFAULT_PORT_NO);

        System.out.println("Server started...");
    } catch (Exception e) {
        try {
            throw new AutoException("AutoServerConnectionException");
        } catch (AutoException e1) {
            e1.printStackTrace();
        }

    }
}

// starting the server
public void startAutoServer() {
    Socket sok;
    while (true) {
        try {
            sok = autoServer.accept();
            defaultSocketClient = new DefaultSocketClient(sok);
            defaultSocketClient.start();
            System.out.println("Connection Established....");
            defaultSocketClient.sendOutput(generateAutoWelcome());
            defaultSocketClient.handleSession();
            defaultSocketClient.closeSession();
        } catch (IOException e) {
            try {
                throw new AutoException("ConnectionException");
            } catch (AutoException e1) {
                e1.printStackTrace();
            }
        }
    }
}

/**
 * This method generates Welcome message for AutoWorld
 */
private String generateAutoWelcome() {
    return "--------Welcome to AutoWorld-----------";
}

}

I am getting the following exception at the server-->

   Exception in thread "main" java.lang.NullPointerException
    at server.DefaultSocketClient.sendOutput(DefaultSocketClient.java:64)
    at server.AutoServerSocket.startAutoServer(AutoServerSocket.java:51)
    at driver.ServerDriver.main(ServerDriver.java:11)

at Line:

  oos.writeObject(newOutput);

I am clearly doing something wrong here as I am not able to receive the object I send at the client side. Can someone please help me?

Thanks

1

There are 1 answers

1
user2641570 On

Your problem comes from there:

   defaultSocketClient = new DefaultSocketClient(sok);
   start();
   System.out.println("Connection Established....");
   sendOutput(generateAutoWelcome() + generateMainMenu());

You are creating a defaultSocketClient to handle the socket created by the client but you don't do anything with it.

Replace these lines by

   defaultSocketClient = new DefaultSocketClient(sok);
   defaultSocketClient.start();
   System.out.println("Connection Established....");
   defaultSocketClient.sendOutput(generateAutoWelcome() + generateMainMenu());

This should solve your NullPointerException bug.

You still have some architecture issues here. You should have a thread for your server socket which loop on sok = autoServer.accept();but you don't have to extend DefaultSocketClient with your server. Your server will basicaly wait for new connection and create new instances of DefaultSocketClient. Your server should also store DefaultSocketClient instance if you want to reuse them later. Otherwise you should just call closeSession() after your sendOutput() call.

This code seems to be for learning purpose so it's fine using basic java sockets but if you wan't to make a real/multiclient/scallable client server app i recommand you use a lib for that.

Java networking libs :

  • Netty Realy powerfull lib but can be hard to configure proberly and is really low level.
  • Kryonet Easy to use with some cool features like object serialisation or host discovery. Hight level lib that can help you create client and server in few lines.