Windows forms and Web forms have two different architectures.
In a windows form, when you modify an image on a control this happens in memory and the framework automatically takes care of repainting the image in the form.
In a web form, you have a client the performs an http request which the server receives and executes code according to the parameters of the request. Once all of the code is execute and http response is returned containing the data output as a result of your code.
In your case, the browser will send the http request and the server will execute the ReciveImg
method which depending on how connected
is implemented might run forever without ever even returning a response to the browser. Even if it does return a response, it would only return the last image you wrote.
To accomplish what you are attempting you need a different approach.
You could have a method which returns a single image for each call. Then within the browser you could repeatedly call that method, perhaps using the legacy AjaxControlToolkit Asp:UpdatePanel configured to refresh as soon as an image is loaded or alternately using a JavaScript loop to repeatedly call your method. This approach can be complicated and not very efficient.
A better option would be to set up a websocket between your client and your server. Once the client connects to the websocket the server can then begin writing images which the client will receive on each message received event. Then within javascript you can set the image to image received from the server. This approach is simpler and more efficient.
For an example of how to implement this, see my repo here which takes screen shots of a desktop and writes them to a websocket on the server side.
Server code:
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);
}
}
Client code (using query and a 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>