我有一个简单的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();
最佳答案
上述问题最简单的解决方案之一是......只需在finally block 中放置一个空检查
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
关于没有发送数据时Java ServerSocket异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775718/