Send a message from client to server - html

I have a server I wrote in NodeJs which listens to port 1234.
From my client (html) I want to send request to my server and wait for an answer.
I tried to use XMLHttpRequest:
var http = new XMLHttpRequest();
var url = "127.0.0.1:1234";
var params = "token=22";
http.open("post", url, true);//"https://www.google.com/search?q=asd"
http.setRequestHeader("Content-type", "text/html");
http.setRequestHeader("Content-length", 0);
http.setRequestHeader("Connection", "keep-alive");
http.onreadystatechange = function() {//Call a function when the state changes.
alert(http.responseText);
}
http.ontimeout = function()
{
alert("timeout");
}
http.timeout=10;
try
{
http.send(null);
}
catch(ex)
{
alert(ex);
}
But I always got exception. The reason was I can't use my own port.
Is There any other way to send request and get respond?

There is nothing wrong with using JQuery.ajax to make your life easier and it does get a lot easier with jquery especially when it comes to XMLHttpRequest.

Related

Microsoft cognitive services face API call

I've build an application on the Azure (microsoft) emotion API, but that was just merged with their cognitive services face API. I'm using a webcam to send an image (in binary data) to their server for analysis, and used to get an xml in return. (I've already commented out some old code, in this example. Trying to get it fixed).
function saveSnap(data){
// Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
var file = data.substring(23).replace(' ', '+');
var img = Base64Binary.decodeArrayBuffer(file);
var ajax = new XMLHttpRequest();
// On return of data call uploadcomplete function.
ajax.addEventListener("load", function(event) {
uploadcomplete(event);
}, false);
// AJAX POST request
ajax.open("POST", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion","image/jpg");
ajax.setRequestHeader("Content-Type","application/json");
//ajax.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml");
ajax.setRequestHeader("Ocp-Apim-Subscription-Key","subscription_key");
ajax.send(img);
}
now I understood from their website the call returns a JSON. But I just can't get it to work. I can see there is data coming back, but how do I even get the JSON out of it. I'm probably missing something essential, and hope someone can help me out. :) the program was working when I could still use the Emotion API.
function uploadcomplete(event){
console.log("complete");
console.log(event);
//var xmlDoc = event.target.responseXML;
//var list = xmlDoc.getElementsByTagName("scores");
console.log(JSON.stringify(event));
A few issues to address:
You'll want to wait for the POST response, not just for the upload
completion.
You'll want to set the content type to be application/octet-stream if you are uploading a binary as you are.
You'll want to set the subscription key to the real value (you probably did before pasting your code here.)
.
function saveSnap(data) {
// Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
var file = data.substring(23).replace(' ', '+');
var img = Base64Binary.decodeArrayBuffer(file);
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
console.log(JSON.stringify(ajax.response));
}
}
ajax.open('post', 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion');
ajax.setRequestHeader('Content-Type', 'application/octet-stream');
ajax.setRequestHeader('Ocp-Apim-Subscription-Key', key);
ajax.send(img);
}

When opening multiple clients, old client does not get updated using nodejs web socket

My goal is when I open a new browser(client), the message sent from the server in the previous client gets updated as well.
Currently,
The clients send messages to the server, the server stores them in localStorage as an array and should send it back to all the clients. All clients should get the same array of messages. It works like ajax call.
As of right now, when I open the first browser, the message is sent to the server and received in the client successfully, and then I open the second one(it works) but the message is not updated in the first browser. PS this acts like a forum, when somebody posts a messages to server, all users should be able to see it.
Here's my code for server:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
// connect to WEBSOCKET server
var socket = io.connect('http://localhost:5000',{'forceNew':true} );
// Fire an event (that the server will handle
socket.emit('myEvent', 'Hello Message from the client');
// Attach event handler for event fired by server
socket.on('server', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML += "<br>" + data; // append data that we got back
});
</script>
</body>
</html>
Here's for client:
//---------------------------------------------------------------
// The purpose is to introduce you to websockets
// This is a SERVER that is SEPARATE from the http server.
//
// Your webpage (in this case the index.html in this directory)
// will be SERVED by the http server. THEN, it will connect to the
// websocket server. Then - they will talk to each other!
//
// Note that in regular http - the server cannot initiate a conversation
// Here, the websocket server sends a message to the client browser.
//
// This example has THREE parts
// 1) The http server code (which is same as what we did earlier)
// 2) This code - this is the web socket server
// It prints what it got from client. It also sends a message to the
// client after every 1 second.
// 3) The html or client code. Note how it connects to the websocket
// and how it sends and receives messages
//
// To RUN THIS EXAMPLE
// First, run node httpServer.js on one terminal
// Next, run node 1_ws.js on another terminal
// Next, type localhost:4000/index.html on some browser
//
//---------------------------------------------------------------
var items=[];
var io = require('socket.io').listen(5000);
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
io.sockets.on('connection', function(socket) {
socket.on('myEvent', function(content) {
//i need to store the content
items.push(content);
localStorage.setItem("list",JSON.stringify(items));
socket.emit('server', JSON.parse(localStorage.getItem("list")));
});
});
I'm running on the local server:( you can ignore the local server if you want, the above code can function on their own)
//---------------------------------------------------------------
// The purpose is to serve a file!
//---------------------------------------------------------------
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var server = http.createServer();
// attach handler
server.on('request', function (req,res) {
var file = path.normalize('.' + req.url);
fs.exists(file, function(exists) {
if (exists) {
var rs = fs.createReadStream(file);
rs.on('error', function() {
res.writeHead(500); // error status
res.end('Internal Server Error');
});
res.writeHead(200); // ok status
// PIPE the read stream with the RESPONSE stream
rs.pipe(res);
}
else {
res.writeHead(404); // error status
res.end('NOT FOUND');
}
});
}); // end server on handler
server.listen(4000);
console.log("start");
You are sending response to only client who sent message to sever only,
To send to all clients which are connected you must use this,
io.emit('server', JSON.parse(localStorage.getItem("list")));
Visit this answer for all
Responses

How to send Data to the client with out client requesting the ws server in nodejs

I need to convert a csv file to json format and send it to a client requesting to ws server in nodejs ,
the file will be updated so many times so i need to send updated data to client
i am able to send data once it is loaded completely(like when app is started it sends all data in file to client) but when i update data in the file the updated data is being printed out on console but it is not being sent to client is their any thing wrong in my code
my node.js code:
var ts = require('tail-stream');
var Converter = require("csvtojson").Converter;
var converter = new Converter({constructResult:false}); //for big csv data
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets server
// we don't have to implement anything.
response.write('hello');
console.log('in http server \n');
});
server.listen(1337, function() { });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
console.log('wsserver');
connection.send('ws server');
converter.on("record_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
connection.send(jsonObj);
});
var tstream = ts.createReadStream('log.csv', {
beginAt: 0,
onMove: 'follow',
detectTruncate: false,
onTruncate: 'end',
endOnError: false
});
tstream.pipe(converter);
});
Right now you are creating a new read stream and adding a listener to the converter on every new connection, that will cause trouble once you have more than one client (same event emitted multiple times, etc..). Instead of that you should keep just one reader and notify all open connections when there's a new record.
Also notice that the library you are using only accepts UTF-8 strings or binary type messages, row objects sent the way you're sending them now will be received as a "[object Object]" string after toString() is called on them. You should probably send just send the row string or use JSON.stringify / JSON.parse.
Try this:
var http = require("http");
var tailStream = require("tail-stream");
var Converter = require("csvtojson").Converter;
var WebSocketServer = require("websocket").server;
var server = http.createServer();
var wsServer = new WebSocketServer({ httpServer: server });
var converter = new Converter({constructResult:false});
var logStream = tailStream.createReadStream("log.csv", { detectTruncate : false });
var connections = [];
server.listen(1337);
logStream.pipe(converter);
//----------------------------------------------------
converter.on("record_parsed", function (jsonObj) {
connections.forEach(function(connection){
connection.send(JSON.stringify(jsonObj));
});
});
//----------------------------------------------------
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
connection.on("close", function() {
connections.splice(connections.indexOf(connection), 1);
});
connections.push(connection);
});
The code above works, tested like this on the client side:
var socket = new WebSocket('ws://localhost:1337/');
socket.onmessage = function (event) {
console.log(JSON.parse(event.data));
}
Note: this doesn't send the whole content of the file at the beginning, just the updates, but you can easily achieve this storing the records and sending them on new connections.

JSONP callback issue

I'm trying to get JSONP working with a server running on an Arduino.
This is my JS code:
window.onload = init;
function init()
{
//alert("Test");
SendRequest();
}
function SendRequest()
{
alert("Sending request");
var url = "http://192.168.1.177";
var request = new XMLHttpRequest();
request.open("GET", url);
request.error = function(e) {
alert("ERROR");
};
request.send(null);
}
function ArduinoJSONP()
{
alert("Callback received!!!");
}
The callback function is never reached.
But if I just direct my browser directly to the Arduino IP I see the following displayed in the browser:
ArduinoJSONP({"data": 12345})
So it seems the server is sending the response with correct JSONP format but somehow the function is not invoked. Is there anything else I need to for JS to call the function? I even tried moving the function to the HTML body but it didn't help either.
Thank you.
You are not handling server response at all. If you doing it without any libraries you need to eval result that was returned by the server.
And actually JSONP implementation is not XHR, you have to inject it as a script tag into html with correct src attribute.
Just use a library that already have all this logic abstracted for you.
Simply inject script tag into HTML tree:
function SendRequest()
{
var element = document.createElement('script');
var s = document.getElementsByTagName('script')[0];
element.type = 'text/javascript';
element.async = true;
element.src = 'http://192.168.1.177';
s.parentNode.insertBefore(element, s);
}
You can mark it with unique id. Hookup to onload event and once executed remove that script.

How to communicate between Air Action Script application and Node.js server

can someone please suggest way to communicate between Air(Action script) App and node.js server?
e.g.
Communication between PHP and Flash(Action Script) application using AMFPHP
BlazeDS for Java+Adobe Flex and Adobe Integrated Runtime (AIR)
Please send me your suggestions, any tutorial, or PoC sample code
Thanks in Advance.
Here is a sample I wrote for a blog. I think the code itself pretty much explains itself.
Client Side AS3 Code :
var urlString:String = "http://localhost:1337/";
function Submit():void
{
var requestVars:URLVariables = new URLVariables();
requestVars.Username = "guest";
var request:URLRequest = new URLRequest();
request.url = urlString;
request.method = URLRequestMethod.GET;
request.data = requestVars;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
try { loader.load(request); }
catch (error:Error) { // Handle Immediate Errors }
}
function loaderCompleteHandler(e:Event):void
{
trace(e.target.data); // Response Text
}
Brief about the code snippet:
We fill in the request data by instantiating a URLVariables class as
requestVars.
We fill in the url & method by instantiating URLRequest class as request.
We attach an load complete event Handler to handle the response.
Wrapping up for catching errors, we call the load method.
URL is set to Localhost port 1337 where the nodeJS would be hosted.
The variable set is a test field UserName which is checked for in the server script.
Server Side NodeJS Code :
var http = require('http'), url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var urlObj = url.parse(req.url, true);
if(urlObj.query["Username"] == "guest") res.end("True");
else res.end("False");
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Brief about the code snippet:
The code listens at port 1337 in the localhost server where it is hosted.
The query string is unwrapped to get the UserName variable & tested.
Server Responds with true since the value equates to guest.