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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I use your suggestion and print out the string decodedText, it is a bunch of gibberish.
Can you show us your c# code for receiving the stream?
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#.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.