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..