user2484067
user2484067

Reputation: 109

Java ServerSocket exception when no data is sent

I have simple Daemon setup with a ServerSocket that listens for a packet, when a connection is made and data is sent, everything works fine, but when a connection is made and NO data is sent, the program crashes with an exception. Here is the code for the Listener thread.

public class Listener implements Runnable {
    ServerSocket listenerSocket;
    Socket connection = null;
    OutputStream out;
    BufferedReader in;
    String packet;
    Console console;
    public Listener(Console Console){
        console = Console;

    }
    @Override
    public void run()
    {
        try{
            listenerSocket = new ServerSocket(5344); //General socket setup
            console.write("INFO", "Listener started");
            do{
            connection = listenerSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
                try{
                    packet = (String)in.readLine(); // Get packet data
                    if(packet != null){
                        byte[] decoded = Base64.decodeBase64(packet);
                        packet = new String(decoded, "UTF-8");
                        Thread handler = new Thread(new Handler(packet, out, console, in, connection)); // Handler class will take / parse packet data
                        handler.start();
                    }
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }while(!packet.equals("shutdown"));
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            try{
                in.close();
                out.close();
                listenerSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
}

This is the error when a connection is made but no data is sent:

Exception in thread "Thread-0" java.lang.NullPointerException
        at com.cj.panel.Listener.run(Listener.java:53)
        at java.lang.Thread.run(Thread.java:744)

Line 53 is in.close();

Upvotes: 0

Views: 76

Answers (3)

Jatin Khurana
Jatin Khurana

Reputation: 1175

One of simplest solution of the above problem is....... Simply put a null check in finally block

finally
{
   if(in!=null)
     in.close();

   if(out!=null)
     out.close();
}

Upvotes: 1

vandale
vandale

Reputation: 3650

if connection = listenerSocket.accept(); or new ServerSocket(5344) throw an exception,then the BufferedReader in will never be initialized, so in the finally block it will throw a null pointer exception

Upvotes: 0

Autocrab
Autocrab

Reputation: 3757

check for in.available() > 0

Upvotes: 0

Related Questions