简体   繁体   中英

UWP with UDP StreamWriter in OSC format

I have following class take care the udp Sending

    public static async Task SendStringUdpAsync(HostName remoteHost,
string remotePort, string message)
    {


        using (var socket = new DatagramSocket())
        {
            var stream = (await socket.GetOutputStreamAsync(
                remoteHost, remotePort)).AsStreamForWrite();
            using (var writer = new StreamWriter(stream))
            {
                await writer.WriteLineAsync(message.ToString());
                await writer.FlushAsync();
            }
        }
    }

But instead send a string, I want to send a custom class in udp

public class OSCString : IOSCValue<string>
{
    static int PaddingLength = 4;

    public string Contents { get; }
    public char TypeTag { get { return 's'; }}
    public byte[] Bytes { get; }



    public OSCString(string contents)
    {
        Contents = contents;
        Bytes = GetBytes();
    }

    public byte[] GetBytes()
    {
        byte[] bytes = new byte[GetByteLength()];
        Encoding.ASCII.GetBytes(Contents, 0, Contents.Length, bytes, 0);
        return bytes;
    }

    public int GetByteLength()
    {
        return GetPaddedLength(Contents.Length);
    }

    public static int GetPaddedLength(int length)
    {
        int terminatedLength = length + 1;
        int paddedLength = (int)(Math.Ceiling(terminatedLength / (float)PaddingLength) * 4);
        return paddedLength;
    }

    public static OSCString Parse(BinaryReader reader)
    {
        List<byte> bytes = new List<byte>();
        byte current = reader.ReadByte();
        while(current != 0)
        {
            bytes.Add(current);
            current = reader.ReadByte();
        }
        string str = Encoding.ASCII.GetString(bytes.ToArray());
        OSCString oscString = new OSCString(str);
        int bytesToBurn = oscString.Bytes.Length - bytes.Count - 1;
        for(int i = 0; i < bytesToBurn; i++)
        {
            reader.ReadByte();
        }
        return oscString;
    }


}

I try DataWriter and StreamWrite, dont work too well.

The UWP take out the socket class, is there any Streamwrite can do the job?

I figure this out

        var socket = new DatagramSocket();

        //socket.MessageReceived += SocketOnMessageReceived;

        using (var stream = await socket.GetOutputStreamAsync(remoteHost, remotePort))
        {
            using (var writer = new DataWriter(stream))
            {
               // var data = Encoding.UTF8.GetBytes(message);

                writer.WriteBytes(packet.Bytes);
                writer.StoreAsync();
            }
        }

Everything works great!!!!!!!!!

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