- Home /
C# TCP server -- cannot call methods or set variables
I am working with C# in Unity 5. I ported some TCP code over from an app I built using .NET 4.5, based heavily on this:
Asynchronous Socket Communication
I am unable to call any methods upon receiving data in the server app.
I receive TCP communication on an event:
public void OnReceivedData(IAsyncResult ar)
{
SocketChatClient client = (SocketChatClient)ar.AsyncState;
byte[] aryRet = client.GetRecievedData(ar);
string aryRetString = System.Text.Encoding.ASCII.GetString(aryRet);
ParseCommand(aryRetString);
if (aryRet.Length < 1)
{
client.Sock.Close();
tcpClients.Remove(client);
return;
}
client.SetupReceiveCallback(this);
}
ParseCommand() is very simple (for testing):
private void ParseCommand(string cmdToParse)
{
string[] splitInput = cmdToParse.Split(',');
testValue++;
Debug.Log(testValue.ToString());
int playerStation = 0;
}
When I use Debug.Log() to output testValue from within ParseCommand, it increments properly each time I call ParseCommand. However, if I continuously output testValue in Update(), it never increments. Also, if I call a method inside of ParseCommand, the method does not fire, and it behaves as though it has exceptioned although no exception is thrown -- i.e., the method stops on that line and the calling method will not fire again.
Answer by Bunny83 · Feb 29, 2016 at 03:35 AM
You are aware of the facts that:
OnReceivedData of an asynchronous Socket connection uses a seperate thread to invoke those callbacks.
Unity isn't threadsafe and you can't call any Unity API method from a different thread then the main thread, event with proper locking since Unity does a thread check inside most API methods which will throw an exception.
Exceptions in other threads might not be caught by Unity or that other thread catches the exception itself.
You also said:
I am unable to call any methods upon receiving data in the server app.
What happens in the server app is completely different from what happens inside Unity unless you use your Unity application as server. If you have two applications communicate through sockets (TCP or whatever) those two applications don't share anything. Neither variables nor methods. They live in two seperate worlds.
From the given information it's not possible to understand who is communicating with what and where you use that snippet of code actually.
If you want a better answer, you should add more details to your question. At the moment it can't be answered.
Your answer
![](https://koobas.hobune.stream/wayback/20220612065623im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
TCP Socket waiting for ipnut to continiue reading data 0 Answers
tcp socket error message (C#) 1 Answer