Client Sockets

I was hoping someone could help me with this. I keep getting a null reference exception when it tries to read in the data from the socket.

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;

public class ClientNetwork : MonoBehaviour {
	public ClientGUI clientgui;

	public bool socketReady = false;
	private TcpClient mySocket;
	private NetworkStream theStream;
	private StreamWriter theWriter;
	private StreamReader theReader;

	void Update()
	{
		string t = this.ReadString();
		if ((t != "") && (socketReady))
		{
			Debug.Log ("Message: " + t);
			if (t.Length < 2) return;
			switch (t.Substring(0,2))
			{
			case "G:": //Packet is for the GUI Manager
				clientgui.OnNetwork(t);
				break;
			case "M:": //Packet is for the Map Manager
				break;
			default:
				break;
			}
		}
	}
	

	void OnApplicationQuit()
	{
		closeSocket();
	}
	
	public bool setupSocket(string Host, int Port)
	{
		try
		{
			mySocket = new TcpClient(Host, Port);
			mySocket.Connect(Host, Port);
			theStream = mySocket.GetStream();
			theWriter = new StreamWriter(theStream);
			theReader = new StreamReader(theStream);
			socketReady = true;
			return true;
		}
		catch (Exception e)
		{
			Debug.Log("Socket error: " + e);
			return false;
		}
	}

	public void WriteString(string theLine)
	{
		if (!socketReady) return;
		String foo = theLine + "

";
theWriter.Write(foo);
theWriter.Flush();
}

	public string ReadString()
	{
	  if ((socketReady) && (mySocket.Connected))
  {
		Debug.Log ("In Read String 1");
		if (theStream.DataAvailable)
			return theReader.ReadLine();
		Debug.Log ("In Read String 2");
      }
		return "";
	}
	
	public void closeSocket()
	{
       if ((socketReady) && (mySocket.Connected))
	{

		theWriter.Close();
		theReader.Close();
		mySocket.Close();
		socketReady = false;
       }
	}
	
}

In any case, I went with this…

using UnityEngine;
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.IO;
using System.Net.Sockets;
using System.Text;

public class ClientNetwork : MonoBehaviour {
	public ClientGUI clientgui;

	private static byte[] recievebuffer = new byte[1024];

	private static Queue<string> RecieveQueue = new Queue<string>();
	private static readonly object RecieveQueueLocker = new object();
	private static readonly object RecieveBufferLocker = new object();
	private static readonly object RecieveThreadLocker = new object();
	private static bool RecieveThreadFree = true;
	private bool socketReady = false;

	private static Socket mySocket;

	void CheckRecieve()
	{
		string msg = string.Empty;
		lock(RecieveQueueLocker)
		{
			if (RecieveThreadFree && RecieveQueue.Count > 0)
			{
				msg = RecieveQueue.Dequeue();
			}
		}

		if (!string.IsNullOrEmpty(msg))
		{
			if (msg.Length >= 2)
			{
				Debug.Log ("Message: " + msg);
	
				switch (msg.Substring(0,2))
				{
				case "G:": //Packet is for the GUI Manager
					clientgui.OnNetwork(msg.Substring(2));
					break;
				case "M:": //Packet is for the Map Manager
					break;
				default:
					break;
				}
			} else
			{
				Debug.Log("Invalid Message Length:"  + msg);
			}
		}
	}

	void Update()
	{
		CheckRecieve();
	}
	

	void OnApplicationQuit()
	{
		closeSocket();
	}
	
	public bool setupSocket(string Host, int Port)
	{
		int attempts = 0;
		
		try
		{
			attempts++;
			mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			mySocket.Connect(Host, Port);
			Debug.Log ("Connected.");
			mySocket.BeginReceive(recievebuffer, 0, recievebuffer.Length, SocketFlags.None, new AsyncCallback(ReaderThread), mySocket);
			Debug.Log ("Reader Thread Started.");
			socketReady = true;
			return true;
		}
		catch (Exception e)
		{
			Debug.Log("Connection attempts: " + attempts.ToString());
			clientgui.OnNetwork("ER:" + e);

		}
		return false;
	}

	public  bool Connected()
	{
		try
		{
			if (mySocket.Connected)
			{
				return true;
			} else
			{
				return false;
			}
		}
		catch (Exception e)
		{
			Debug.Log ("Socket Error on Connection Check: " + e);

			//clientgui.OnNetwork("ER:" + e);

			return false;
		}
	}

	private static void ReaderThread (IAsyncResult AR)
	{
		try
		{
			Socket socket = (Socket)AR.AsyncState;
			//Socket socket = mySocket;
			int recieved = socket.EndReceive(AR);
			byte[] dataBuf = new byte[recieved];
			Array.Copy(recievebuffer, dataBuf, recieved);
			string text = Encoding.ASCII.GetString(dataBuf);
			lock(RecieveQueueLocker)
			{
				RecieveQueue.Enqueue(text);
			}
			try
			{
				mySocket.BeginReceive(recievebuffer, 0, recievebuffer.Length, SocketFlags.None, new AsyncCallback(ReaderThread), mySocket);
			}
			catch (Exception e)
			{
				Debug.Log("(Reader Thread: Start Next) Socket error: " + e);
				//clientgui.OnNetwork("ER:" + e);
			}
		}
		catch (Exception e)
		{
			Debug.Log("(Reader Thread: Begin) Socket error: " + e);
			//clientgui.OnNetwork("ER:" + e);

		}
	}

	private static void WriterThread (IAsyncResult AR)
	{
		Socket socket = (Socket)AR.AsyncState;
		socket.EndSend(AR);
	}

	public void WriteString(string theLine)
	{
		byte[] data = Encoding.ASCII.GetBytes(theLine);
		try
		{
			mySocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(WriterThread), mySocket);
			Debug.Log("Sent: " + theLine);
		}
		catch (Exception e)
		{
			Debug.Log("(Network: WriteString) Socket error: " + e);
			clientgui.OnNetwork("ER:" + e);

		}
	}

	public void closeSocket()
	{
		if (!socketReady)
			return;
		try
		{
			mySocket.Close();
		}
		catch (Exception e)
		{
			Debug.Log("Close Socket Failed: " + e);
		}
		socketReady = false;
	}

}

The problem is most likely in your setupSocket function. If it’s crashing on 73 or 74, that most likely means the streams are null, so the connection didn’t work. I’d place a if(mySocket.Connected) check before pulling the streams, and on the else do a warning or error log to the console so you can see that the connection failed.

Did you read and understand the replies you’ve already had?

You say you’re connecting to 127.0.0.1:123 - is there anything listening for a connection on that port on your machine? I expect not.

As I and others have said - it is most likely that you do not have a valid connection and that your streams, writers and readers are all in an invalid state to be used.

Check that you have an established connection before using the TcpClient connection. (ie. if(mySocket.Connected) {/* have connection */})

You need to have a valid connection (connected to something, not some random port that has no process listening for connections)).

Also - are you using Unity Pro (or trial) since I think you need Pro to use C# sockets - I could be wrong here though.