David Fernández
David Fernández

Reputation: 544

Calls to Socket.send in little time causes two different data to be sent in same packet

I'm programming a game which sends the position of the player to the server whenever the player moves, using XML like this:

<?xml version="1.0" encoding="utf-8" ?> <request type="movement"> <character map="1" coords="10,20"/> </request>

The thing is, since the information is sent very fast, it usually sends two or three times the XML in the same packet and then the server cannot parse it correctly.

In the client side, using C# .net I create a new Task in order to send the info so that it continues to update the game correctly, in the task I simply call Socket.send to send XML as a text string.

Client:

Byte[] bytesToSend = Encoding.ASCII.GetBytes(texto);
socket.Send(bytesToSend, bytesToSend.length, 0);

Java Server:

public String convertStreamToString(InputStream is) throws Exception {
        BufferedInputStream reader = new BufferedInputStream(is);
        byte[] ent = null;
        int recivido;
        // String line = reader.readLine();
        do {
            ent = new byte[reader.available()];


            recivido = reader.read(ent);
        } while (recivido == 0);

        return new String(ent);
    }

Upvotes: 0

Views: 190

Answers (1)

jgauffin
jgauffin

Reputation: 101140

TCP works like that since it's stream based and not message based.

Read my answer here: Application stops when receiving info through socket

Client side:

var buffer = Encoding.UTF8.GetBytes(yourXml);
var header = BitConverter.GetBytes(buffer.Length);
socket.Send(header);
socket.Send(buffer);

Server side:

var header = new byte[4];
var received = socket.Receive(header, 0, 4);
var xmlBuffer = new byte[BitConverter.ToInt32(header)];
socket.Receive(xmlBuffer, 0, xmlBuffer.Length);

Note that you have to keep Receiving until you really got 4 bytes and then the number of bytes received in the length header. (I did not do that in my example)

Upvotes: 1

Related Questions