[HELP] Client slowly handling custom TCP server packets
Hi!
Introduction:
There have been few days since I had this problem and I have not been able to solve it:
I have a custom Java TCP multithreaded server that interacts with my Unity client. For example client sends "login user pass" packet and Server instantly (and I must mention this now) answers with an "ok" or "fail". There are no problems here.
My methods:
Previous "receive" code on Client.cs
private void Update()
{
if (socketReady)
{
if (socket.GetStream().DataAvailable) //the problem was this line
{
string recv = encryption(sr.ReadLine());
if (recv != null)
HandleRecv(recv);
}
}
}
HandleRecv() method that interacts with Unity Objects
private bool HandleRecv(string recv) //handles different packets received from server
{
string[] cmd = recv.Split(' ');
switch (cmd[0])
{
case "fail":
GameManager.Instance.BackButton(); //Here I change scene
Debug.Log("Wrong credentials or logged in already!");
break;
// etc, i will just post this as example
}
return true;
}
The problem:
The first code I used for Client was a lot simpler and seemed quicker. I could interact with server without any problems. However, once I created the "move" packets (which are a continuous fluctuation of packets almost instantly) I noticed that I could not receive 2 or more packets in a row because of the socket.getStream().DataAvailable line.
I deleted that line, ok. But then, as the Update() method is the main class thread, when the server didn't send any packets to the client, the game freezed waiting for one.
So I had to change the code: I removed Update() and created a Recv() thread to act the same way. As this thread was not the main one, the game did not freeze.
But what happened then? My HandleRecv() method checks the packet that has been received and then INTERACTS WITH UNITY OBJECTS (changes scene, creates game objects, etc.). As this new Recv() thread is not the main thread, I CANNOT INTERACT with those objects.
What can I do?
I have thought of multiple solutions, the one I thought for example (but doesnt work well): Using the Update() thread again and creating public variables that are accessed between the 2 threads but this SLOWS A LOT the packet handling! My player movement seems lagged...
Actual "receive" code on Client.cs (UGLY share of public variable between 2 threads, SLOWS A LOT the game, seems lagged)
public string recv = null;
public bool handled = true;
public void Recv() //Thread that reads line from server stream
{
if (socketReady)
while (true)
{
if (handled)
{
handled = false;
recv = encryption(sr.ReadLine());
}
}
}
private void Update() //once public variable gets updated, handle it
{
if (socketReady)
if (recv != null)
if (HandleRecv(recv))
{
handled = true;
recv = null;
}
}
I would really appreciate your help!! Thank you in advance!!