rlabrecque / Steamworks.NET

Steamworks wrapper for Unity / C#
http://steamworks.github.io
MIT License
2.84k stars 371 forks source link

Change SteamNetworkingSockets send and receive message to support byte[] #411

Open J0K0SAN opened 3 years ago

J0K0SAN commented 3 years ago

Hi, first of all thanks for the amazing work!

I think it would be great if the SteamNetworkingSockets.SendMessageToConnection would accept a byte[] as input and SteamNetworkingSockets.ReceiveMessagesOnConnection a byte[][].

I don't really get how to work with the IntPtr. I have a byte array, how to write/read the IntPtr, how to free it?

The steamworks API use the SteamNetworkingMessage_t struct how to get it?

J0K0SAN commented 3 years ago

After a few hours of research i've found a way, it's probably not the best, but it works. I thought i'd share it here for anyone having the same trouble as me.


IntPtr sendBuffer = Marshal.AllocHGlobal(65536);

void SendMessage(byte[] message)
{
    try
    {
        long messageNumber;
        Marshal.Copy(message, 0, sendBuffer, message.Length);
        SteamNetworkingSockets.SendMessageToConnection(connection, sendBuffer, message.Length, 0, out messageNumber);
    }
    catch
    {
        Marshal.FreeHGlobal(sendBuffer);
    }
}

IntPtr[] receiveBuffers = new IntPtr[16];

void ReceiveMessage()
{
    int messageCount = SteamNetworkingSockets.ReceiveMessagesOnConnection(connection, receiveBuffers, receiveBuffers.Length);
    for (int i = 0; i < messageCount; i++)
    {
        try
        {
            SteamNetworkingMessage_t netMessage = Marshal.PtrToStructure<SteamNetworkingMessage_t>(receiveBuffers[i]);
            byte[] message = new byte[netMessage.cbSize];
            Marshal.Copy(netMessage.m_pData, message, 0, message.Length);
            foreach (NetworkingListener listener in networkingListeners)
                listener.MessageReceived(message);
        }
        finally
        {
            Marshal.DestroyStructure<SteamNetworkingMessage_t>(receiveBuffers[i]);
        }
    }
}
GBPierce commented 3 years ago

@J0K0SAN Thank you so much for sharing this, I was stuck on how to handle this for quite some time. :)