我目前正在做一个小项目,使用tcp网络套接字创建会议应用程序。
我发现编码和解码字符串并将数据从服务器发送到客户端非常困难。我正在尝试将图片框图像发送给客户。
流程中涉及的方法和语句:( drawBox是图片框)
private void SaveSnapshot()
{
Bitmap bmp = new Bitmap(drawBox.ClientSize.Width, drawBox.ClientSize.Height);
drawBox.DrawToBitmap(bmp, drawBox.ClientRectangle);
OnUpdatedDrawing(ImageToBase64(bmp, ImageFormat.Bmp));
};
public string ImageToBase64(Bitmap image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToString(imageBytes);
return base64String;
}
}
private void Drawboard_OnUpdatedDrawing(string data)
{
BroadCast("Draw|" + data);
}
private void BroadCast(string data)
{
foreach(var socket in Clients)
{
try { socket.Send(Encoding.ASCII.GetBytes(data)); }
catch (SocketException SE) { MessageBox.Show("Error: " + SE.Message, "Error"); }
}
}
case "Draw":
this.Invoke(() =>
{
byte[] NewBytes = Convert.FromBase64String(command[1]); // Contains the base 64 string of the picture box bitmap
MemoryStream ms1 = new MemoryStream();
Drawboard.drawBox.Image = Image.FromStream(ms1);
Drawboard.drawBox.Refresh();
});
错误:参数无效。错误来自:
private void ReadCallback(IAsyncResult AR)
{
try
{
var buffer = (byte[])AR.AsyncState;
var receive = _Socket.EndReceive(AR);
if (receive != 0)
{
var data = Encoding.ASCII.GetString(buffer, 0, receive);
this.OnReceived(this, data);
}
else
{
this.OnDisconnected(this);
this.isConnected = false;
this.Close();
return;
}
this._Socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReadCallback, buffer);
}
catch (Exception ex)
{
OnErrorReceived(this, ex.Message + "\n\nError connecting to the server");
}
}