0

我想在java中创建一个简单的客户端/服务器应用程序,它有一个主要启动线程 - 侦听器线程和可运行 - 发送器线程。 他们与一个工作程序进行通信。 套接字是在侦听器线程上创建的,就像输入和输出静态变量一样。为什么在写入到另一个线程定义的套接字输出时会出现(java)NullPointerException异常?

问题是: 我可以使用输出,但只有当我从它定义的侦听器线程中调用它时。 (output.writeBytes(“0000”);) 当我尝试从发件人runnable调用它时,我得到一个空异常! (InfoListener.output.writeBytes( “0000”);)

这里是我的(没有那么聪明)的代码,没有所有的异常处理:

* InfoListener.java文件*

public class InfoListener extends Thread { 

    public int port = 5000; 
    public Socket socket = null; 
    static BufferedReader input; 
    static DataOutputStream output; 
    static boolean can_start_sender = false; 

    static boolean active = true; 
    static String answer=""; 

    public void run() 
    {    
     // init socket 
     socket = new Socket("127.0.0.1", port); 
     output = new DataOutputStream(socket.getOutputStream()); 
     input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
     can_start_sender = true; 

     while (active) // while main app is active 
     { 
      // Read new data!! 
      answer = input.readLine(); 
      if (answer!=null) 
      { 
       System.out.println("Info : Listener received : " + answer); 
      } 
     } 
    } 
} 

* InfoSender.java文件*

public class InfoSender implements Runnable { 


    static InfoListener infoListener; 
    static InfoSender infoSender; 
    static String string_to_send = "0000"; 

    public static void main(String[] args) 
    { 
     // start listener 
     infoListener = new InfoListener(); 
     infoListener.start(); 

     // Start Sender 
     infoSender = new InfoSender(); 
     infoSender.run(); 

     while (infoListener.isAlive()) 
      Thread.sleep(100); 
    } 

    public void run() 
    { 
     //attempt to connect to the server and send string 
     // Wait for socket 
     while (InfoListener.can_start_sender = false) 
      Thread.sleep(100); 

     // write -------- HERE IS THE NULLPOINTEREXCEPTION ------------ 
     InfoListener.output.writeBytes(string_to_send); 
     System.out.println("Info : info sent :"+ string_to_send); 

     // wait a bit for listener to get response back, then close 
     Thread.sleep(10000); 
     InfoListener.active = false; 
     } 
} 

请帮助: |

+0

这些字段都不应该是静态的。 – EJP

回答

1

while (InfoListener.can_start_sender = false) 

要分配给falsecan_start_sender。因此while将始终解析为false

是下面的代码while

// write -------- HERE IS THE NULLPOINTEREXCEPTION ------------ 
InfoListener.output.writeBytes(string_to_send); 

,对其他Thread之前有时间来初始化staticoutput场从而导致NullPointerException得到执行这是可能的。

使用

while (!InfoListener.can_start_sender) 

或更好,但使用CountDownLatch或类似java.util.concurrent锁定对象。您还应该制作can_start_sendervolatile

+0

非常感谢 - 我的noob错误:NullPointerException已解决,但不知何故,我没有得到它的另一边,直到我关闭发件人和听众..我会解决它..:{ –

+0

@HaimRimon不要忘记在你的'OutputStream'实例上调用'flush()'。 –

+0

对于关闭:我没有得到它的另一端,因为我使用了readline,并没有发送一个“\ n”的结尾,所以信息没有到达,直到我关闭输出的套接字。 :) –

相关问题