简体   繁体   中英

Sending base64 string via socket c#

I'm trying to send base64 encoded image.

Client code:

private void button1_Click(object sender, EventArgs e)
    {
        IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(ipEndPoint);
        Bitmap printScreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Graphics g = Graphics.FromImage(printScreen as Image);
        g.CopyFromScreen(0, 0, 0, 0, printScreen.Size);
        MemoryStream ms = new MemoryStream();
        printScreen.Save(ms, ImageFormat.Jpeg);
        client.Send(Encoding.UTF8.GetBytes(Convert.ToBase64String(ms.ToArray())));
        client.Shutdown(SocketShutdown.Both);
    }

Server code:

const int BUFFER_SIZE = 2048;
static byte[] buffer = new byte[BUFFER_SIZE];
static void ReceiveCallback(IAsyncResult AR)
    {
        Socket current = (Socket)AR.AsyncState;
        int received = current.EndReceive(AR);
        if (received > 0)
        {
            s += Encoding.UTF8.GetString(buffer);
            current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        } else
        {
            Console.WriteLine(s.Length);
            var bytes = Convert.FromBase64String(s);
            using (var imageFile = new FileStream("test.jpg", FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }
            s = "";
        }
    }

But the picture is often not transmitted. Usually this error occurs: "The input data is not valid Base-64 string".

How to solve this problem? Big thanks!

received tells you how many bytes in the buffer are currently valid . The overload of GetString you're using converts all bytes in the buffer.

You can switch to passing explicit index and count:

s += Encoding.UTF8.GetString(buffer,0,received);

Note, also, that this technique you're using isn't generally safe, but should be for the base-64 subset of characters. Not all UTF-8 characters occupy a single byte and TCP offers no guarantee that you won't only get part of a character returned by one call of Receive whilst the remaining bytes of that character would be delievered (hopefully 1 ) by the next call.

(And Matthew's comment about this all being rather odd since you could just send the bytes directly, too)


1 I don't mean here that the bytes will be lost. Merely that there are few guarantees offered here so you're not guaranteed that the next call will receive all of the remaining bytes for the character.

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