简体   繁体   中英

client server socket structured message c#

Helllo guys, I'm creating client-server game using sockets. I'm trying to use structured messages, then serialize and deserialize them, there is 3 strings in my structure. My code serializes first string, but mess up two following ones. I been told that my structure might have enough space space only for one string.

My message structure:

public struct Message_PDU
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10101)]
    public string commandID;
    public string playerIndex;
    public string score;
}; 

Serialize method

     private byte[] Serialize(Object myObject)
    {
        int size = Marshal.SizeOf(myObject);
        IntPtr ip = Marshal.AllocHGlobal(size); //allocate unmanaged memory equivelent to the size of the object
        Marshal.StructureToPtr(myObject, ip, false); //marshal the object into the allocated memory
        byte[] byteArray = new byte[size];
        Marshal.Copy(ip, byteArray, 0, size); //place the contents of memory into a byte[]
        Marshal.FreeHGlobal(ip); //free unmanaged memory
        return byteArray;
    }

Sending message code:

            String szdata1 = "--";
            String szdata2 = AlliasText.Text;
            String szdata3 = "1";



            Message_PDU myPDU = new Message_PDU();
            myPDU.commandID = szdata1;
            myPDU.playerIndex = szdata2;
            myPDU.score = szdata3;
            byte[] byData = Serialize(myPDU); //convert structure into a byte[]
            m_ClientSocket.Send(byData, SocketFlags.None);

I tried to increase SizeConst, but it didn't work. Debugging shows that only first string gets serialized. Thank you

thank for trying to help. My course leader helped me to sort it out. Basically, I marshalized only first string instead of each one of them, because I thought that I am marshalizing whole structure.

Message structure should look like this:

public struct Message_PDU
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 101)]
public string commandID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 101)]
public string playerIndex;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 101)]
public string score;
}; 

Also, SizeConst is just charachters length sent in the message, and it's important to make as short as possible. Thank you again, I hope it helps someone in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM