browser does't receive the reponse that tokio TcpStream write - rust

i tried use tokio(tokio={version="1", features=["full"]}) to implement a simple http server. The code is below. The weired thing is the server can receive the request from browser, but the brower can't receive the response from the server. Is there any bug in my code?
use tokio::{self, net};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
async fn process(mut stream: TcpStream) {
let mut buf = [0u8; 4096];
loop {
let n = stream.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
let s = String::from_utf8_lossy(&buf[0..n]).to_string();
print!("{}", s);
if s.ends_with("\r\n\r\n") {
println!("request received");
break;
}
}
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>
";
println!("response");
// browser doesn't receive the response that this line of code send.
stream.write(response_str.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
println!("response DONE");
}
#[tokio::main]
async fn main() {
let listener = net::TcpListener::bind("127.0.0.1:9998").await.unwrap();
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move{
process(stream).await;
});
}
}

there need a extra line separator between status line and entity body. the browser can pase the response when the response_str like this
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>"

Related

iter_mut() doesn't run whenever I try to add status in Bevy 0.8.1

I added collision between the player and the ground, and I want to add a jumping mechanic into my game with on_ground. However, whenever I try to add status, it just stops iterating entirely.
fn collision_detection(
ground: Query<&Transform, (With<Ground>, Without<Player>)>,
mut player: Query<(&mut Transform, &mut PlayerStatus), With<Player>>,
) {
let player_size = Vec2::new(PLAYER_SIZE_X, PLAYER_SIZE_Y);
let ground_size = Vec2::new(GROUND_SIZE_X, GROUND_SIZE_Y);
for ground in ground.iter() {
for (mut player, mut status) in player.iter_mut() {
if collide(
player.translation,
player_size,
ground.translation,
ground_size,
)
.is_some()
{
status.on_ground = true;
println!("ON GROUND")
} else {
status.on_ground = false;
}
if status.on_ground {
player.translation.y += GRAVITY;
}
}
}
}
For some reason, this part wouldn't run
for (mut player, mut status) in player.iter_mut() {
if collide(
player.translation,
player_size,
ground.translation,
ground_size,
)
.is_some()
{
status.on_ground = true;
println!("ON GROUND")
} else {
status.on_ground = false;
}
if status.on_ground {
player.translation.y += GRAVITY;
}
}
It works if I only do this though:
for mut player in player.iter_mut() {
if collide(
player.translation,
player_size,
ground.translation,
ground_size,
)
.is_some()
{
player.translation.y += GRAVITY;
}
}
If you have only one player, you can use get_single_mut() instead of iter_mut() on the query.
It returns a result, so you can check in your function easily whether the player entity had been found at all. And if not send yourself some nice debugging message :)
if let Ok((mut player, mut status)) = player.get_single_mut() {
// do your collision check
} else {
// player not found in the query
}
https://docs.rs/bevy/latest/bevy/prelude/struct.Query.html#method.get_single_mut
Edit:
Looking at your comment above: if you have an already spawn entity you can always add new components to it using .insert_bundle or .insert.

Using AnmiateCC html5 output with Haxe

Because FLASH is Dead I have a mission to convert some games to work as html5.
Graphics and animation is made on timeline in AnimateCC.
Until now the process looks like: publish to swc/swf, FlashDevelop -> AddToLibrary and I've access to all the objects.
When publish target is HTML5 canvas I have two files:
testHaxe.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>testHaxe</title>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="testHaxe.js"></script>
<script>
var canvas, stage, exportRoot;
function init() {
canvas = document.getElementById("canvas");
images = images||{};
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", handleFileLoad);
loader.addEventListener("complete", handleComplete);
loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt) {
if (evt.item.type == "image") { images[evt.item.id] = evt.result; }
}
function handleComplete(evt) {
exportRoot = new lib.testHaxe();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
}
</script>
</head>
<body onload="init();" style="background-color:#D4D4D4;margin:0px;">
<canvas id="canvas" width="550" height="400" style="background-color:#FFFFFF"></canvas>
</body>
</html>
testHaxe.js
(function (lib, img, cjs, ss) {
var p; // shortcut to reference prototypes
lib.webFontTxtFilters = {};
// library properties:
lib.properties = {
width: 550,
height: 400,
fps: 24,
color: "#FFFFFF",
webfonts: {},
manifest: [
{src:"images/Bitmap1.png", id:"Bitmap1"}
]
};
lib.webfontAvailable = function(family) {
lib.properties.webfonts[family] = true;
var txtFilters = lib.webFontTxtFilters && lib.webFontTxtFilters[family] || [];
for(var f = 0; f < txtFilters.length; ++f) {
txtFilters[f].updateCache();
}
};
// symbols:
(lib.Bitmap1 = function() {
this.initialize(img.Bitmap1);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,103,133);
(lib.в1 = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Warstwa 1
this.instance = new lib.Bitmap1();
this.instance.setTransform(-2,-2);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-2,-2,103,133);
// stage content:
(lib.testHaxe = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Layer 1
this.instance = new lib.в1();
this.instance.setTransform(85,90,1,1,0,0,0,49.5,64.5);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(308.5,223.5,103,133);
})(lib = lib||{}, images = images||{}, createjs = createjs||{}, ss = ss||{});
var lib, images, createjs, ss;
I'm looking for a way to connect thouse files into haxe and access files on Stage or from library ex: new a1();
There are externs for createJS in haxeLib but I don't know how to use them with this output.
You can write externs for your generated lib, eg.:
package lib;
import createjs.MovieClip;
#:native("lib.B1")
extern class B1 extends MovieClip {
}
#:native("lib.testHaxe")
extern class TextHaxe extends MovieClip {
public var instance:B1;
}
Obviously that could be very tedious so I wrote a tool for it:
https://github.com/elsassph/createjs-def
And posted a complete example here: http://philippe.elsass.me/2013/05/type-annotations-for-the-createjs-toolkit/
However it's currently broken for recent versions of Animate CC because the JS output has changed - it needs to be fixed.

xamarin.forms webview baseurl not working on device (iOS 10.1)

I have a xamarin.forms app that uses HybridWebView (https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/hybridwebview/) to display an html document. I use baseUrl to load local css and js into the document. This code was working fine on iOS 9.x.
But, after I upgraded to iOS 10, the code works on the iOS simulator but not on the actual device. On the device, it does not load the css from local storage.
here is the test code I am using. It works on simulator but not on device.
async void Handle_TestButtonClicked (object sender, System.EventArgs e)
{
string css = #"
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
";
var folder = await AppGlobals.AppStorage.GetContentFolder ();
string filename = "styles.css";
await AppGlobals.AppStorage.WriteToFile (folder, filename, css);
string html = #"<!DOCTYPE html>
<html>
<head>
<link rel=""stylesheet"" href=""styles.css"">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>";
this.DocumentView.Html = html;
}
In the HybridWebView, I am using the following code to set the baseUrl
if (Element.Html != null) {
string baseFolderPath = await AppStorage.GetInstance ().GetContentFolderPath ();
var baseUrl = new NSUrl (baseFolderPath, true);
Control.LoadHtmlString (Element.Html, baseUrl);
}
I am using PCLStorage library to read/write to local storage.
I think LoadHtmlString is broken for loading local css/js etc.
I worked around this problem by writing the HTML string to local file and then loading it using LoadFileUrl. This works as expected
if (!String.IsNullOrEmpty (Element.Uri)) {
string filePath = await GetFilePathInContentFolderFromUri (Element.Uri);
var fileUrl = new NSUrl (filePath, false);
Control.LoadFileUrl (fileUrl, fileUrl);
}
Another work-around could be to inject the required css/js into the html document itself and still use LoadHtmlString, this works.

Using The Media object to record and play back audio files on a device

Hi i try to use the phoneGap Media object to play audio content but i'm getting this error
Uncaught ReferenceError:Media is not defined i'm getting this example of code from phonegap Documentation http://docs.phonegap.com/en/1.0.0/phonegap_media_media.md.html
I'm using the code below :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Media Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
</head>
<body>
<a href="#" class="btn large"
onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_
_rockGuitar.mp3');">Play Audio</a>
Pause Playing Audio
Stop Playing Audio
<p id="audio_position"></p>
</body>
</html>
Any idea please , thank u very much
The link u r providing for playing sound is not working properly when I am opening the link in a browser I m not able to play sound.
So kindly store ur rockGuitar.mp3 inside your assets/www folder and while playing that file provide the src of the file as
src= "/android_asset/www/rockGuitar.mp3";
newMedia= new Media(src,onSuccess1,onError);
Or provide working link in the src of sound.

SWFUpload asp.net return new filename of uploaded files

I'm trying to implement SWFUpload for uploading images on my page. The file-path is stored in a table with a unique id as key and the file is store on the server with a new filename. I need the id or the filename to be returned so that I can access that information when I later-on need it. Is this possible and how is it done? Maybe i could update a asp:label?
I have the following code:
upload.aspx.cs
(I haven't implemented the database saving yet as I want to know if this is possible first)
protected void Page_Load(object sender, EventArgs e)
{
try
{
// Get the data
HttpPostedFile postedfile = Request.Files["Filedata"];
int n = 0;
string fullPath;
while (true)
{
fullPath = Server.MapPath("Img\\") + n.ToString() + RemoveSpecialChars(postedfile.FileName);
if (File.Exists(fullPath))
{
n++;
}
else
{
postedfile.SaveAs(fullPath);
break;
}
}
}
catch
{
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally
{
Response.End();
}
}
default.aspx
<!--
Image upload
-->
<script type="text/javascript" src="Scripts/swfupload.js"></script>
<script type="text/javascript" src="Scripts/handlers.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "Upload.aspx",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit: "5120", //5MB
file_types: "*.jpg",
file_types_description: "JPG Images",
file_upload_limit: 0, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
swfupload_preload_handler: preLoad,
swfupload_load_failed_handler: loadFailed,
file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete,
// Button settings
button_image_url: "Style/Images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '<span class="button">Välj bilder</span>',
button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,
// Flash Settings
flash_url: "swfupload.swf", // Relative to this file
flash9_url: "swfupload_FP9.swf", // Relative to this file
custom_settings: {
upload_target: "divFileProgressContainer"
},
// Debug Settings
debug: false
});
}
</script>
default.aspx
<div id="swfu_container" style="margin: 0px 10px;">
<div>
<span id="spanButtonPlaceholder"></span>
</div>
<div id="divFileProgressContainer" style="height: 75px;"></div>
</div>
Thanks.
I found the solution:
If i look inside handlers.js (provided by swfupload) I can catch whats is returned from the upload.aspx.cs
Inside upload.aspx.cs write:
protected void Page_Load(object sender, EventArgs e)
{
try
{
// Get the data
HttpPostedFile postedfile = Request.Files["Filedata"];
Response.Write((postedfile.FileName); //Returns filename to javascript
}
catch
{
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally
{
Response.End();
}
}
}
Inside handler.js (downloaded from demo page) replace uploadSuccess with:
function uploadSuccess(file, serverData) {
try {
alert(serverData);
addImage("thumbnail.aspx?id=" + serverData);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setStatus("Thumbnail Created.");
progress.toggleCancel(false);
} catch (ex) {
this.debug(ex);
}
}

Resources