Web client
Establishing a connection
In this sample, we use Moscrif native class WebClient. It connects web server and client device and opens a port on the web server. This is done through WebClient.open method. In order to do this, host and port have to be specified.
// Create web client (download from https://moscrif.com/userfiles/moscrif2.png) var wc = new WebClient(); // connect to the server
wc.open("moscrif.com", 80, false, "");
Data downloading
In this case, retrieving data from server via GET method is sufficient. We just need to use WebClient.GetData with picture source and picture name as parameter.
//get picture from the server (from [server address]/userfiles/moscrif2.png)
wc.getData("/userfiles/moscrif2.png");
Events processing
To handle all possible scenarios during connection and communication between web server and client, WebClient supports following events:
- onCancel
- onError
- onReceived
- onReceiving
- onSending
// show error message if some error appeared
wc.onError = function() {
System.messageBox("An error appeared. Please check internet conection.\n Error message: " + this.errorMessage);
this super.invalidate();
}
// show number of received bytes
wc.onReceiving = function(received, total) {
// total can be 0, depends on the server behaviour
this super._text = String.printf("receved %d bytes...", received);
this super.invalidate();
}
wc.onCancel = function() {
this super._text = "cancelled!";
this super.invalidate();
}
Data decoding
Once we received data from the web server, we transfer it into bitmap object by Bitmap.fromBytes method where the parameter of this method is received content.
// show image, when it is downloaded
wc.onReceived = function() {
// transfer dota into bitmap
this super._img = Bitmap.fromBytes(this.data);
this super.invalidate();
}
User interface
To display received image from the web server we declare an Window.onDraw method. Drawing on the mobile device screen is done by Canvas.drawBitmap native feature of Moscrif. We can decorate displaying text by Paint native feature of Moscrif.
app.onDraw = function(sender, canvas)
{
// fill whole screen by white color
canvas.clear(0xffffffff);
// if image has been downloaded show it
if (this._img) {
var x = (System.width - this._img.width) / 2;
var y = (System.height - this._img.height) / 2;
canvas.drawBitmap(this._img, x, y);
// othewise show text
} else {
var (h, w) = this._paint.measureText(this._text);
canvas.drawText(this._text, (System.width - w)/2, (System.height - h)/2, this._paint);
}
}
|