1

I'm coding a game with Unity and I was wondering how can I receive data from my server without knowing how much i will get.

Until now I was using this to communicate with the server :

public string buffer;
// client is a class where I store the TCPclient and the NetworkStream (it should be called server but I didn't change it)
    private void sendToClient(string message)
    {
        byte[] response = new byte[256];
        byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

        buffer = string.Empty;
        client.stream.Write(data, 0, data.Length);
        client.stream.Read(response, 0, response.Length);
        buffer = System.Text.Encoding.ASCII.GetString(response).ToString();
    }

The problem is that the server can send me informations about ennemies on the map but it depends on the number of enemies on the map. If there is only one I receive his position, but if there are 2 I receive 2 times the positions until the number of informations overflow the response variable.

So I was wondering how can I do this with a good method.

Edit:

I was able to fix my problem with the use of
StreamWriter and StreamReader from the System.IO namespace

  • This really depends on your data structure and how the server is sending notifications of the end of data. TCP is just raw data and has no built in way to say the data is complete. check out https://stackoverflow.com/a/2390150/574722 – hawkstrider Jun 16 '22 at 14:36
  • 4
    One very common approach is to send a fixed-size header before any message, that contains the size of the message payload (and possibly other information like its type). – Ben Voigt Jun 16 '22 at 14:48
  • Does this answer your question? [How should I mark the end of a TCP packet?](https://stackoverflow.com/questions/2389756/how-should-i-mark-the-end-of-a-tcp-packet) – Ruzihm Jun 17 '22 at 16:20
  • Thank you for your comments but I found another method with StreamReader and StreamWriter (much easier and very easy to setup, I don't need to change things from my server) – Rémy Noulin Jun 17 '22 at 21:18

0 Answers0