Windows 窗体和 Web 窗体具有两种不同的体系结构。
在 Windows 窗体中,当您修改控件上的图像时,这会发生在内存中,并且框架会自动负责重新绘制窗体中的图像。
在 Web 表单中,您有一个客户端执行一个 http 请求,服务器接收该请求并根据请求的参数执行代码。执行完所有代码并返回包含代码输出数据的 http 响应。
在您的情况下,浏览器将发送 http 请求,服务器将执行 ReciveImg 方法,这取决于 connected 的实现方式可能会永远运行,甚至不会向浏览器返回响应。即使它确实返回了响应,它也只会返回你写的最后一张图片。
要完成你正在尝试的事情,你需要一种不同的方法。
-
您可以有一个方法为每次调用返回一个图像。然后在浏览器中,您可以重复调用该方法,可能使用配置为在加载图像后立即刷新的旧版 AjaxControlToolkit Asp:UpdatePanel,或者使用 JavaScript 循环重复调用您的方法。这种方法可能很复杂,而且效率不高。
-
更好的选择是在您的客户端和服务器之间设置websocket。一旦客户端连接到 websocket,服务器就可以开始写入图像,客户端将在收到的每个消息事件中接收这些图像。然后在 javascript 中,您可以将图像设置为从服务器接收到的图像。这种方法更简单、更高效。
有关如何实现此功能的示例,请参阅my repo here,它会截取桌面屏幕截图并将其写入服务器端的 websocket。
服务器代码:
class Program
{
static bool running = false;
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the WebSocketServer!");
Console.ReadKey();
Console.WriteLine();
var appServer = new WebSocketServer();
//Setup the appServer
if (!appServer.Setup(2012)) //Setup with listening port
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
}
appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived);
appServer.NewSessionConnected += AppServer_NewSessionConnected;
Console.WriteLine();
//Try to start the appServer
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
running = true;
Console.WriteLine("The server started successfully, press key 'q' to stop it!");
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
//Stop the appServer
running = false;
Console.WriteLine();
Console.WriteLine("The server was stopped!");
Console.ReadKey();
}
private static void AppServer_NewSessionConnected(WebSocketSession session)
{
byte[] bytes = null;
var fps = 1000 / 12.0;
while (running && session.Connected)
{
DateTime start = DateTime.Now;
bytes = ScreenShotUtility.TakeScreenshot();
var segment = new ArraySegment<byte>(bytes);
session.Send(segment);
var diff = DateTime.Now.Subtract(start).TotalMilliseconds;
var sleep = Math.Max(0, fps - diff);
System.Threading.Thread.Sleep((int)sleep);
}
}
static void appServer_NewMessageReceived(WebSocketSession session, string message)
{
//Send the received message back
session.Send("Server: " + message);
}
}
客户端代码(使用查询和 websocket):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var noSupportMessage = "Your browser cannot support WebSocket!";
var ws;
var canvas;
var ctx;
var urlCreator;
function wsMessage(e) {
if (typeof e.data === "string") {
appendMessage("# " + evt.data + "<br />");
}
else if (e.data instanceof ArrayBuffer) {
} else if (e.data instanceof Blob) {
//showBlob(e.data);
blob2canvas(e.data);
}
}
function appendMessage(e) {
$('#lastMessage').html(e);
}
function blob2canvas(blob) {
var img = new Image();
img.onload = function () {
if (canvas.width != img.width)
canvas.width = img.width;
if (canvas.height != img.height)
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = urlCreator.createObjectURL(blob);// blob;
}
function showBlob(blob) {
//console.log(blob);
var imageUrl = urlCreator.createObjectURL(blob);
document.querySelector("#blobImage").src = imageUrl;
//disconnectWebSocket();
}
function connectSocketServer() {
var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);
if (support == null) {
appendMessage("* " + noSupportMessage + "<br/>");
return;
}
appendMessage("* Connecting to server ..<br/>");
// create a new websocket and connect
var host = "localhost"; //"192.168.1.170"; //"localhost" <-- broke for edge, so is "127.0.0.1";
ws = new window[support]('ws://'+host +':2012/');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
wsMessage(evt);
}
ws.onerror = function (event) {
console.error("WebSocket error observed:", event);
};
// when the connection is established, this method is called
ws.onopen = function () {
appendMessage('* Connection open<br/>');
$('#messageInput').attr("disabled", "");
$('#sendButton').attr("disabled", "");
$('#connectButton').attr("disabled", "disabled");
$('#disconnectButton').attr("disabled", "");
};
// when the connection is closed, this method is called
ws.onclose = function () {
appendMessage('* Connection closed<br/>');
$('#messageInput').attr("disabled", "disabled");
$('#sendButton').attr("disabled", "disabled");
$('#connectButton').attr("disabled", "");
$('#disconnectButton').attr("disabled", "disabled");
}
}
function sendMessage() {
if (ws) {
var messageBox = document.getElementById('messageInput');
ws.send(messageBox.value);
messageBox.value = "";
}
}
function disconnectWebSocket() {
if (ws) {
ws.close();
}
}
function connectWebSocket() {
connectSocketServer();
}
window.onload = function () {
$('#messageInput').attr("disabled", "disabled");
$('#sendButton').attr("disabled", "disabled");
$('#disconnectButton').attr("disabled", "disabled");
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
urlCreator = window.URL || window.webkitURL;
}
</script>
</head>
<body>
<input type="button" id="connectButton" value="Connect" onclick="connectWebSocket()" /> <input type="button" id="disconnectButton" value="Disconnect" onclick="disconnectWebSocket()" /> <input type="text" id="messageInput" /> <input type="button" id="sendButton" value="Send" onclick="sendMessage()" /> <br />
<div id="lastMessage"></div>
<img id="blobImage" />
<canvas id="canvas" height="500" width="500"></canvas>
</body>
</html>