質問

this is my server side code for sending data to client:

public bool SendMessage(Socket socket, byte[] message, string logMessage = "Unknow")
    {
        try
        {
            MsgTemp msg = new MsgTemp(socket, logMessage, message);

            System.Diagnostics.Trace.WriteLine(" send ---------- " + message.Length.ToString());

            socket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendCallBack), msg /* null*/);
            return true;
        }
        catch
        {
            // :) removed
        }
        return false;
    }

and this code is receive callback method in client:

private void ReceiverCallBack(IAsyncResult ar)
    {
        try
        {
            int size = _socket.EndReceive(ar);
            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiverCallBack), null);

            System.Diagnostics.Trace.WriteLine(" received ---------- " + size.ToString());

            // messagereceived is an event
            if (MessageReceived != null)
            {
                byte[] temp = new byte[size];
                Array.Copy(_buffer, temp, size);

                MessageReceived(temp);
            }
        }
        catch (Exception exp)
        {
            // :) removed
        }

    }

when server send many packages to client data goes invalid. (in normal/low transaction work correctly)

see this (bytes was sent between server an client in a conversation) :

send ---------- 496 
received ---------- 496
send ---------- 613
received ---------- 613
send ---------- 680
received ---------- 680
send ---------- 227
send ---------- 697
received ---------- 227
send ---------- 722
send ---------- 710
received ---------- 697
received ---------- 1432

two last packages was sent to client received in one package -> 722 + 710 = 1432 and data goes invalid/unusable...

why ? thanks

役に立ちましたか?

解決

This is how TCP works - it's a stream protocol. The bytes are guaranteed to be received in exactly the order they are sent, but you can Receive the data of multiple Send operations at once, or receive the data of one Send operation in two Receives.

You'll have to somehow define what a message is - it's common to first send the size of a message, followed by the message payload.

See for example http://blog.stephencleary.com/2009/04/message-framing.html - it contains a good explanation of the why, the how and code examples. There are many other examples available online.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top