I can see you’re using sync sockets to send/'recieve data. In that case you would want to have a method that will check the RecievedBuffer property. If the property is lesser or equal to zero no data was received from the server , otherwise you can process data normaly.
I wouldn’t recommend TCPListener , it’s a bad abstraction that combines few methods into one.
Tho , i’d pretty much use async sockets , unless you have specific needs to use sync sockets. Here’s an example of async receiving.
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
public class Client : MonoBehaviour {
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
private void SetupServer()
{
try
{
_clientSocket.Connect(new IPEndPoint(IPAddress.Loopback,6670));
}
catch(SocketException ex)
{
Debug.Log(ex.Message);
}
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void ReceiveCallback(IAsyncResult AR)
{
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = _clientSocket.EndReceive(AR);
if(recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);
//Process data here the way you want , all your bytes will be stored in recData
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data,0,data.Length);
_clientSocket.SendAsync(socketAsyncData);
}
}
So in async socketing , you would have RecieveCallback , and in the recieve callback you’re checking if you actually received data from the server by calling EndAccept method and passing the IAsyncResult parameter.
After that you copy your recieved buffer into a buffer that has a set value of recieved bytes , this way you avoid null bytes in your buffer.
Also note that when doing async socketing you’re making multiple threads , and cross threads operation are not supported with unity components , so you will have to queue actions to the main thread in order to execute them , or you can make bunch of classes to control the scene that indirectly manipulate unity components.
Hopefully this will help , hope to hear from you soon!