Search code examples
c#socketsudpavro

Send a stream obj through UDP client with Avro framework in C#


I am trying to send a stream through UDP socket. The "SendTo" takes byte[] buffer argument. Not sure how to do this if I have a stream object (buffer). Please help! Thanks. The ByteBufferOutputStream does not seem to have a funciton to convert the stream to bytes.

ByteBufferOutputStream buffer = new ByteBufferOutputStream();
Avro.IO.Encoder ej = new BinaryEncoder(buffer);
ej.WriteInt(Convert.ToInt32(testEvent["schemaId"]));
var dwrd = new DefaultWriter(schema);
dwrd.Write<GenericRecord>(testEvent, ej);
buffer.Flush();
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);

IPAddress serverAddr = IPAddress.Parse("192.168.1.1");
IPEndPoint endPoint = new IPEndPoint(serverAddr, 2190);

clientSocket.SendTo(buffer, endPoint);

Solution

  • Actually it does. ByteBufferOutputStream has a method named GetBufferList, which returns an IEnumerable of System.IO.MemoryStream. You can take these MemoryStreams, and concatenate them to a single buffer, with an integer header specifying how many streams are there (denoted by X), followed by X more integers specifying the length of the ordered streams, followed by the streams themselves.

    You can send that entire buffer via UDP to your server, where it will reconstruct the streams, and use ByteBufferInputStream (from Avro) which has a constructor that accepts them.