没有数据发送时的Java ServerSocket异常

时间:2013-12-25 18:40:07

标签: java sockets

我有一个简单的Daemon设置,用于监听数据包的ServerSocket,当建立连接并发送数据时,一切正常,但是当建立连接并且没有数据发送时,程序崩溃除了。这是Listener线程的代码。

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

这是建立连接但没有发送数据时的错误:

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)

第53行是in.close();

3 个答案:

答案 0 :(得分:1)

上述问题最简单的解决方案之一是.......简单地在finally块中进行空检查

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

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

答案 1 :(得分:0)

检查in.available() > 0

答案 2 :(得分:0)

如果connection = listenerSocket.accept();new ServerSocket(5344)抛出异常,则BufferedReader in将永远不会被初始化,因此在finally块中它将抛出空指针异常