none
Anybody know if Socket.Receive will stop receive bytes at CR & LF? RRS feed

  • Question

  • I try to use Socket.Receive to receive bytes from server, but i cannot receive the whole data. Only front part of the bytes and stop at CR&LF.

    the below is the screeshot i got from Matlab. From the pic, you can see that i can receive the whole data from server. But i can only receive the bytes before CR&LF in C# socket. Anybody know why that happen? Maybe any internal setting to stop receiving at CR&LF?

    the below is the C# code i use to receive data. thanks!

    /// <summary>
    /// This method requests the response from Salus server. 
    /// </summary>
    public string SocketSendReceive(string request)
    {
        Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
        Byte[] bytesReceived = new Byte[9600];
        string response = "";
    
        if (this.m_SalusTcp == null)
            return ("Server Connection failed!");
    
        try
        {
            // Send request to the server.
            this.m_SalusTcp.Send(bytesSent, bytesSent.Length, 0);
    
            // Receive the server response. 
            int bytes = 0;
            THRD.Thread.Sleep(1000);
            bytes = this.m_SalusTcp.Receive(bytesReceived, m_SalusTcp.Available, SocketFlags.None);
            response = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "SocketSendReceive", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    
        return response;
    }
    
    i checked that the bytes value is 15. After that, every byte in bytesReceived array is 0.


    Kevin

    Tuesday, June 18, 2013 12:10 AM

Answers

  • TCP breaks all messages into datagrams aproximately 1500 bytes max.  Also during routing the datagrams can get futher divided.  A connection wil stay open forever and you shouldn't close the connection until an command is sent and achnowledged from the far end.  TCP can route datagrams of a long message through different servers. 

    In theory, you can make a connection from NY to London and some of the datagrams will be routed across the Atlantic Ocean and some across the Pacific Ocean.  If the client closes the connection, it is posible that the connection will close before all the packets arrive taking the long path.

    So here is what you must do

    1) If you are sending ascii data then each message should be sent with a '\n' and on the receive end read until the CR is reaches (or some other EOF terminator).

    2) When sending binary data you must put add to the begining of each message a 4 or 8 bytes header indicating the number of bytes that are being transmitted.

    3) The receiver must loop until the end of data is reached by either method 1 or 2 above.


    jdweng

    Tuesday, June 18, 2013 12:25 AM