0

In python, I convert a dictionary to a json string, use standard python encoding, then use base64 to further encode for sending over a socket like this.

item.data is a list of dicts. myconverter is there to handle datetime.

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP

def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()


async def main_loop() 

....

    async for item in streamer.listen():
        for index, quoteDict in enumerate(item.data):
            quote = json.dumps(quoteDict, default = myconverter)

            sock.sendto(base64.b64encode(quote.encode('ascii')),  (UDP_IP, UDP_PORT))

When I use python to get the data sent over a socket like this, everything works fine:

import socket
import json
import base64


UDP_IP = "127.0.0.1"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(16384) # buffer size is 16384 bytes
    quote_dict = base64.b64decode(data)
    print(quote_dict)

What is the equivalent section of C# code that decodes the python enconded datagram above?

Ivan
  • 7,448
  • 14
  • 69
  • 134
  • 3
    Possible duplicate of [How do I encode and decode a base64 string?](https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string) – gunr2171 Oct 16 '18 at 19:05

2 Answers2

1

You can decode a base 64 encoded string with the Convert class.

byte[] inputBytes = Convert.FromBase64String(inputText);
string decodedText = System.Text.ASCIIEncoding.ASCII.GetString(inputBytes);

Important

The FromBase64String method is designed to process a single string that contains all the data to be decoded. To decode base-64 character data from a stream, use the System.Security.Cryptography.FromBase64Transform class.

Michael G
  • 6,695
  • 2
  • 41
  • 59
0

I got it to work by:

Removing the conversion to base64 in python by doing this:

sock.sendto(quote.encode('UTF-8'),  (UDP_IP, UDP_PORT)) 

Then in C#, I just use this function:

static string GetString(byte[] bytes) {
           return Encoding.UTF8.GetString(bytes); }

Now I can read the data both from python and C#.

Ivan
  • 7,448
  • 14
  • 69
  • 134