- Home /
Client TCP - State of the art
Hi,
I created a easy small TCP client in Unity.
During all the game this client will receive tcp command async.
Here is the function to receive the data :
public void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
if (recv > 0)
{
treatOutput(System.Text.Encoding.ASCII.GetString(data, 0, recv));
mySocket.BeginReceive(data,0,data.Length,0,new AsyncCallback(ReceiveData), mySocket);
}
else
{
Debug.Log("No more data - the socket should be closed");
}
}
My Question is related to the function treatOutput(myCommand) :
If I execute this command in the main thread of Unity and refresh the UI, it won't work ('cause you can not modify the UI outside the main thread)
So I pass the command via a static variable
private static Queue qDataCommand ;
private void treatOutput (string myCommand)
{
qDataCommand.Enqueue(myCommand);
}
public static string getData()
{
if (qDataCommand.Count > 0) return (string)qDataCommand.Dequeue();
else return "";
}
And call getData() every frame in the UI :
public class MyUI: MonoBehaviour {
public MyUI() {}
void Start () {
void Update () {
string command = FrontController.getData() ;
if (command != "")
{
Label myText = (Label)(GameObject.Find("myLabel")).GetComponent<Label>();
myText.Text = command;
}
}
}
Is there another way ? I feel it's extremely costly and not really nice.
Thanks in advance for any advice
Oli
I don't know if my question is tricky, but it seems that people don't use async tcp connection.
If I ask my question differently :
When you check your socket do you make it directly or indireclty always via the update() method ?
Please post comments as CO$$anonymous$$$$anonymous$$ENTS NOT as answers!
On the third "script" you posted (which has nothing to do with the question) you shouldn't be using Find
at runtime, only during initialization.
For asynchronous connections you should be using a callback function that does all the work for you (calls the appropriate functions etc)
Thanks for your return.
And thanks for pointing out "the find" that has to be declared in the start function.
Well my question was not clear enough :
I make the callback in the receiveData
I add the data in a queue (I am in the callback thread)
I read the queue from the update gameobject (and dequeue it). And it's obviously done in the main thread.
How can I directly modify the gameobject from the callback ?