将Base64字符串从C#传输到Python,反之亦然

时间:2016-05-30 19:29:42

标签: c# python base64

我正在构建一个包含通过套接字传输文件的项目。我的服务器是用python编写的,我的客户端是用C#编写的。由于Python在字符集方面并不是非常友好,我通过将文件转换为base64并在python中解码来传输我从客户端上传的文件。它完美地运作。出于某种原因,当我做相反的事情时,当我在python中编码文本并在传输后解码它会引发错误。 看一看 - 这是从客户端到服务器的正确发送:

List<byte> b = Encoding.ASCII.GetBytes(Convert.ToBase64String(cont)).ToList();
int size = Encoding.ASCII.GetByteCount(st) + b.Count;
string pack = size + ":" + st;
buffer = Encoding.ASCII.GetBytes(pack);
List<byte> a = buffer.ToList();
a.AddRange(b);
connection.Send(a.ToArray());

和python:

base64.b64decode(params[2])

这很有效。 当我做相反的事情时(使用相同的库会产生错误):

string res = SendRecv("1?" + basepath + v[0]);
res = res.Remove(res.Length - 1).Substring(1);//because it is sent quoted

byte[] converted = Convert.FromBase64String(res.Replace(" ",String.Empty));
saved.Write(converted, 0, converted.Length);
saved.Close();

SendRecv(send和recv)方法:

    private void Send(string st)
    {
        int size = Encoding.ASCII.GetByteCount(st);
        string pack = size + ":" + st;
        buffer = Encoding.ASCII.GetBytes(pack);
        connection.Send(buffer);
    }
    private string Recv()
    {
        try
        {
            buffer = new byte[2];
            connection.Receive(buffer, 2, SocketFlags.Partial);
            string header = Encoding.ASCII.GetString(buffer, 0, 2);
            while (!header.Contains(":"))
            {
                connection.Receive(buffer, 2, SocketFlags.Partial);
                header += Encoding.ASCII.GetString(buffer, 0, 2);
            }
            int size = int.Parse(header.Split(':')[0]);
            string mes0 = header.Split(':')[1];
            buffer = new byte[size];
            int b = 0;
            int s = (size >= 2048) ? 2048 : size;
            while(size-s > 0)
            {
                connection.Receive(buffer,b,s,SocketFlags.None);
                size -= s;
                s = (size >= 2048) ? 2048 : size;
                b += s;
            }
            connection.Receive(buffer, size, SocketFlags.None);
            string fullmes = mes0 + Encoding.ASCII.GetString(buffer);


            return fullmes;
        }
        catch(Exception e)
        {
            MessageBox.Show(e.ToString());
        }
        return "";
    }
    private string SendRecv(string a)
    {
        Send(a);
        return Recv();
    }

的Python:

return base64.b64encode(self.finalResult.getContent())

它引发了这个例外:

  

输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非空白字符

0 个答案:

没有答案