简体   繁体   中英

Null Reference Exception when object is clearly defined

I'm using Unity and .NET to create a TCP client-server relationship.

I actually have everything working where I can send messages back and forth, but now I am hitting a NullReferenceException that is got me scratching my head.

I have a function in my TCPClientListener in my Unity code that calls ReadSocket every Update()

public void SetupSocket(){
      socket = new TcpClient(host, port);
      stream = socket.GetStream();
      writer = new StreamWriter(stream);
      reader = new StreamReader(stream);
      socketReady = true;

}

public string ReadSocket(){
   if(stream.DataAvailable){
      return "New Data! " + reader.ReadLine().Replace("<EOF>", "");
   }
   return "";
}

The above works fine, no problem. WHen the server sends a message, I receive it just fine. But then I add a very simple if statement, and now I'm getting NullReferenceException in regards to reader.

public string ReadSocket() {
        if (stream.DataAvailable) {
            if (reader.ReadLine().Contains("<EOF>"))
                return "New data! " + reader.ReadLine().Replace("<EOF>", "");
        }
        return "";
    }

I hope that I have just been looking at this too long to see the obvious. Why does

if (reader.ReadLine().Contains("<EOF>"))

give me an error!? If I remove it, no error..

The immediate bug is that you are reading two lines. The second read appears to return null. You could have found this by applying standard NRE debugging techniques.

Another bug is that you assume that TCP preserves bessage boundaries. If DataAvailable > 0 this does not mean that an entire line is available. There might be just one byte available. You might find your game blocking unexpectedly.

Usually, it is best to have a continuous read loop running and never pool for data. Just read. When a new line is received act on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM