Question
Please answer the question correctly and quickly. Please show code and the result output of the code. Required code to solve is given below SATIC
Please answer the question correctly and quickly. Please show code and the result output of the code. Required code to solve is given below
SATIC SERVER CODE
/*Exercise: if the user types the title of a song that the server has,
the server should send a JSON object back to the client to replace
the words array in the client app.
*/
//hard coded songs to serve client
var peacefulEasyFeeling = [];
peacefulEasyFeeling.push({word: "I", x:50, y:50});
peacefulEasyFeeling.push({word: "like", x:70, y:50});
peacefulEasyFeeling.push({word: "the", x:120, y:50});
peacefulEasyFeeling.push({word: "way", x:170, y:50});
peacefulEasyFeeling.push({word: "your", x:230, y:50});
peacefulEasyFeeling.push({word: "sparkling", x:300, y:50});
peacefulEasyFeeling.push({word: "earrings", x:430, y:50});
peacefulEasyFeeling.push({word: "lay", x:540, y:50});
var sisterGoldenHair = [];
sisterGoldenHair.push({word: "Well", x:50, y:50});
sisterGoldenHair.push({word: "I", x:110, y:50});
sisterGoldenHair.push({word: "tried", x:130, y:50});
sisterGoldenHair.push({word: "to", x:190, y:50});
sisterGoldenHair.push({word: "make", x:220, y:50});
sisterGoldenHair.push({word: "it", x:290, y:50});
sisterGoldenHair.push({word: "Sunday", x:320, y:50});
var brownEyedGirl = [];
brownEyedGirl.push({word: "Hey", x:40, y:50});
brownEyedGirl.push({word: "where", x:100, y:50});
brownEyedGirl.push({word: "did", x:180, y:50});
brownEyedGirl.push({word: "we", x:220, y:50});
brownEyedGirl.push({word: "go", x:260, y:50});
brownEyedGirl.push({word: "Days", x:40, y:100});
brownEyedGirl.push({word: "when", x:110, y:100});
brownEyedGirl.push({word: "the", x:190, y:100});
brownEyedGirl.push({word: "rains", x:240, y:100});
brownEyedGirl.push({word: "came", x:320, y:100});
var songs = {"Peaceful Easy Feeling" : peacefulEasyFeeling,
"Sister Golden Hair" : sisterGoldenHair,
"Brown Eyed Girl" : brownEyedGirl
};
//Server Code
var http = require('http'); /eed to http
var fs = require('fs'); /eed to read static files
var url = require('url'); //to parse url strings
var counter = 1000; //to count invocations of function(req,res)
var ROOT_DIR = 'html'; //dir to serve static files from
var MIME_TYPES = {
'css': 'text/css',
'gif': 'image/gif',
'htm': 'text/html',
'html': 'text/html',
'ico': 'image/x-icon',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'js': 'text/javascript', //should really be application/javascript
'json': 'application/json',
'png': 'image/png',
'txt': 'text/plain'
};
var get_mime = function(filename) {
var ext, type;
for (ext in MIME_TYPES) {
type = MIME_TYPES[ext];
if (filename.indexOf(ext, filename.length - ext.length) !== -1) {
return type;
}
}
return MIME_TYPES['txt'];
};
http.createServer(function (request,response){
var urlObj = url.parse(request.url, true, false);
console.log(' ============================');
console.log("PATHNAME: " + urlObj.pathname);
console.log("REQUEST: " + ROOT_DIR + urlObj.pathname);
console.log("METHOD: " + request.method);
var receivedData = '';
//attached event handlers to collect the message data
request.on('data', function(chunk) {
receivedData += chunk;
});
//event handler for the end of the message
request.on('end', function(){
console.log('received data: ', receivedData);
console.log('type: ', typeof receivedData);
//if it is a POST request then echo back the data.
if(request.method == "POST"){
var dataObj = JSON.parse(receivedData);
console.log('received data object: ', dataObj);
console.log('type: ', typeof dataObj);
//Here we can decide how to process the data object and what
//object to send back to client.
//FOR NOW EITHER JUST PASS BACK AN OBJECT
//WITH "text" PROPERTY
//TO DO: return the words array that the client requested
//if it exists
console.log("USER REQUEST: " + dataObj.text );
var returnObj = {};
returnObj.text = 'NOT FOUND: ' + dataObj.text;
//object to return to client
response.writeHead(200, {'Content-Type': MIME_TYPES["text"]}); //does not work with application/json MIME
response.end(JSON.stringify(returnObj)); //send just the JSON object
}
});
if(request.method == "GET"){
//handle GET requests as static file requests
var filePath = ROOT_DIR + urlObj.pathname;
if(urlObj.pathname === '/') filePath = ROOT_DIR + '/index.html';
fs.readFile(filePath, function(err,data){
if(err){
//report error to console
console.log('ERROR: ' + JSON.stringify(err));
//respond with not found 404 to client
response.writeHead(404);
response.end(JSON.stringify(err));
return;
}
response.writeHead(200, {'Content-Type': get_mime(filePath)});
response.end(data);
});
}
}).listen(3000);
console.log('Server Running at http://127.0.0.1:3000 CNTL-C to quit');
CANVAS
var words = [];
words.push({word: "I", x:50, y:50});
words.push({word: "like", x:70, y:50});
words.push({word: "the", x:120, y:50});
words.push({word: "way", x:170, y:50});
words.push({word: "your", x:230, y:50});
words.push({word: "sparkling", x:300, y:50});
words.push({word: "earrings", x:430, y:50});
words.push({word: "lay", x:540, y:50});
var movingString = {word: "Moving",
x: 100,
y:100,
xDirection: 1, //+1 for leftwards, -1 for rightwards
yDirection: 1, //+1 for downwards, -1 for upwards
stringWidth: 50, //will be updated when drawn
stringHeight: 24}; //assumed height based on drawing point size
//indended for keyboard control
var movingBox = {x: 50,
y: 50,
width: 100,
height: 100};
var wayPoints = []; //locations where the moving box has been
var timer;
var wordBeingMoved;
var deltaX, deltaY; //location where mouse is pressed
var canvas = document.getElementById('canvas1'); //our drawing canvas
function getWordAtLocation(aCanvasX, aCanvasY){
//locate the word near aCanvasX,aCanvasY
//Just use crude region for now.
//should be improved to using lenght of word etc.
/ote you will have to click near the start of the word
//as it is implemented now
for(var i=0; i if(Math.abs(words[i].x - aCanvasX) Math.abs(words[i].y - aCanvasY) } return null; } var drawCanvas = function(){ var context = canvas.getContext('2d'); context.fillStyle = 'white'; context.fillRect(0,0,canvas.width,canvas.height); //erase canvas context.font = '20pt Arial'; context.fillStyle = 'cornflowerblue'; context.strokeStyle = 'blue'; for(var i=0; i var data = words[i]; context.fillText(data.word, data.x, data.y); context.strokeText(data.word, data.x, data.y); } movingString.stringWidth = context.measureText( movingString.word).width; //console.log(movingString.stringWidth); context.fillText(movingString.word, movingString.x, movingString.y); //draw moving box context.fillRect(movingBox.x, movingBox.y, movingBox.width, movingBox.height); //draw moving box way points for(i in wayPoints){ context.strokeRect(wayPoints[i].x, wayPoints[i].y, movingBox.width, movingBox.height); } //draw circle context.beginPath(); context.arc(canvas.width/2, //x co-ord canvas.height/2, //y co-ord canvas.height/2 - 5, //radius 0, //start angle 2*Math.PI //end angle ); context.stroke(); } function handleMouseDown(e){ //get mouse location relative to canvas top left var rect = canvas.getBoundingClientRect(); //var canvasX = e.clientX - rect.left; //var canvasY = e.clientY - rect.top; var canvasX = e.pageX - rect.left; //use jQuery event object pageX and pageY var canvasY = e.pageY - rect.top; console.log("mouse down:" + canvasX + ", " + canvasY); wordBeingMoved = getWordAtLocation(canvasX, canvasY); //console.log(wordBeingMoved.word); if(wordBeingMoved != null ){ deltaX = wordBeingMoved.x - canvasX; deltaY = wordBeingMoved.y - canvasY; //document.addEventListener("mousemove", handleMouseMove, true); //document.addEventListener("mouseup", handleMouseUp, true); $("#canvas1").mousemove(handleMouseMove); $("#canvas1").mouseup(handleMouseUp); } // Stop propagation of the event and stop any default // browser action e.stopPropagation(); e.preventDefault(); drawCanvas(); } function handleMouseMove(e){ console.log("mouse move"); //get mouse location relative to canvas top left var rect = canvas.getBoundingClientRect(); var canvasX = e.pageX - rect.left; var canvasY = e.pageY - rect.top; wordBeingMoved.x = canvasX + deltaX; wordBeingMoved.y = canvasY + deltaY; e.stopPropagation(); drawCanvas(); } function handleMouseUp(e){ console.log("mouse up"); e.stopPropagation(); //$("#canvas1").off(); //remove all event handlers from canvas //$("#canvas1").mousedown(handleMouseDown); //add mouse down handler //remove mouse move and mouse up handlers but leave mouse down handler $("#canvas1").off("mousemove", handleMouseMove); //remove mouse move handler $("#canvas1").off("mouseup", handleMouseUp); //remove mouse up handler drawCanvas(); //redraw the canvas } //JQuery Ready function -called when HTML has been parsed and DOM //created //can also be just $(function(){...}); //much JQuery code will go in here because the DOM will have been loaded by the time //this runs function handleTimer(){ movingString.x = (movingString.x + 5*movingString.xDirection); movingString.y = (movingString.y + 5*movingString.yDirection); //keep inbounds of canvas if(movingString.x + movingString.stringWidth > canvas.width) movingString.xDirection = -1; if(movingString.x if(movingString.y > canvas.height) movingString.yDirection = -1; if(movingString.y - movingString.stringHeight drawCanvas() } //KEY CODES //should clean up these hard coded key codes var ENTER = 13; var RIGHT_ARROW = 39; var LEFT_ARROW = 37; var UP_ARROW = 38; var DOWN_ARROW = 40; function handleKeyDown(e){ console.log("keydown code = " + e.which ); var dXY = 5; //amount to move in both X and Y direction if(e.which == UP_ARROW && movingBox.y >= dXY) movingBox.y -= dXY; //up arrow if(e.which == RIGHT_ARROW && movingBox.x + movingBox.width + dXY movingBox.x += dXY; //right arrow if(e.which == LEFT_ARROW && movingBox.x >= dXY) movingBox.x -= dXY; //left arrow if(e.which == DOWN_ARROW && movingBox.y + movingBox.height + dXY movingBox.y += dXY; //down arrow var keyCode = e.which; if(keyCode == UP_ARROW | keyCode == DOWN_ARROW){ //prevent browser from using these with text input drop downs e.stopPropagation(); e.preventDefault(); } } function handleKeyUp(e){ console.log("key UP: " + e.which); if(e.which == RIGHT_ARROW | e.which == LEFT_ARROW | e.which == UP_ARROW | e.which == DOWN_ARROW){ var dataObj = {x: movingBox.x, y: movingBox.y}; //create a JSON string representation of the data object var jsonString = JSON.stringify(dataObj); $.post("positionData", jsonString, function(data, status){ console.log("data: " + data); console.log("typeof: " + typeof data); var wayPoint = JSON.parse(data); wayPoints.push(wayPoint); for(i in wayPoints) console.log(wayPoints[i]); }); } if(e.which == ENTER){ handleSubmitButton(); //treat ENTER key like you would a submit $('#userTextField').val(''); //clear the user text field } e.stopPropagation(); e.preventDefault(); } function handleSubmitButton () { var userText = $('#userTextField').val(); //get text from user text input field if(userText && userText != ''){ //user text was not empty var userRequestObj = {text: userText}; //make object to send to server var userRequestJSON = JSON.stringify(userRequestObj); //make json string $('#userTextField').val(''); //clear the user text field //Prepare a POST message for the server and a call back function //to catch the server repsonse. //alert ("You typed: " + userText); $.post("userText", userRequestJSON, function(data, status){ console.log("data: " + data); console.log("typeof: " + typeof data); var responseObj = JSON.parse(data); movingString.word = responseObj.text; //replace word array with new words if there are any if(responseObj.wordArray) words = responseObj.wordArray; }); } } $(document).ready(function(){ //This is called after the broswer has loaded the web page //add mouse down listener to our canvas object $("#canvas1").mousedown(handleMouseDown); //add key handler for the document as a whole, not separate elements. $(document).keydown(handleKeyDown); $(document).keyup(handleKeyUp); timer = setInterval(handleTimer, 100); //timer.clearInterval(); //to stop drawCanvas(); });
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started