我正在尝试将图像从Javascript客户端发送到C#服务器并将该图像保存在文件中。 Websocket已建立,我可以将消息从客户端发送到服务器。 该消息是我从Javascript中的imagedata获取的字节数组。 我的服务器获取字节数组,但是当我尝试将字节数组转换为图像时,我得到了System.ArgumentException:“ Invalid Parameter”。 这是我来自Javascript客户端的代码:
var context = canvas.getContext('2d');
ar data2 = context.getImageData(0, 0, 800, 600).data;
var byteArray = new Array(data2);
connection.send(data);
这是我在C#服务器上的代码:
private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
string headerResponse = "";
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
var i = client.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
// write received data to the console
Console.WriteLine(headerResponse);
}
if (client != null)
{
/* Handshaking and managing ClientSocket */
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1]
.Replace("\r", "").Split('\n')[0]
.Trim();
// key should now equal dGhlIHNhbXBsZSBub25jZQ==
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
//+ "Sec-WebSocket-Version: 13" + newLine
;
client.Send(Encoding.UTF8.GetBytes(response));
var i = client.Receive(buffer); // wait for client to send a message
using (Image image = Image.FromStream(new MemoryStream(buffer)))
{
image.Save("output.png", ImageFormat.Png);
}
}
}
catch (SocketException exception)
{
throw exception;
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}
当我尝试创建新的Memorystream(buffer)时发生我的异常。 有人可以帮助您解决此问题吗? 谢谢!