【发布时间】:2018-04-27 20:42:41
【问题描述】:
我正在尝试发送 base64 编码的图像。
客户端代码:
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);
}
服务器代码:
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 = "";
}
}
但图片通常不会传输。 通常会出现这个错误: “输入数据不是有效的 Base-64 字符串”。
如何解决这个问题? 非常感谢!
【问题讨论】:
-
为什么? Base64 不仅仅是发送它编码的字节。
-
当您可以发送原始二进制数据时,为什么还要发送 base64?
-
我知道。只是具体的任务。