Node.js: Sending server response fails - javascript

I am building a node.js server which receives data on a specific port. This works pretty fine, but I'm not able to send a response afterwards.
Server:
http.createServer(function(sock) {
sock.on('data', function(data) {
console.log('DATA: ' + data);
sock.write(' saved in the DB');
db.serialize(function(){
db.run("INSERT INTO Data values('" + data + "')");
});
});
}).listen(PORT, HOST);
Error:
http://i.stack.imgur.com/TzeHJ.png
Thanks,
Benedikt

It looks like you want to be using net.createServer() instead:
var net = require('net');
net.createServer(function(sock) {
// code here that uses the socket
});

Related

How to push live data from nodejs server to AngularJS?

I have successfully opened a websocket connection in server to an external API to get exchange ticker data but not sure how to continuously push the data to client / AngularJS.
Here is the router code:
router.get('/live-ticker', function(req, res) {
var autobahn = require('autobahn');
var wsuri = "wss://api.poloniex.com";
var connection = new autobahn.Connection({
url: wsuri,
realm: "realm1"
});
connection.onopen = function(session) {
function tickerEvent(args, kwargs) {
res.json(args);
console.log(args);
}
session.subscribe('ticker', tickerEvent);
}
connection.onclose = function() {
console.log("Websocket connection closed");
}
connection.open();
});
What I'm attemping to do is to have the data from tickerEvent live update the controller in the front end:
app.controller('liveTickerController', function($scope, $http) {
$scope.ticker = [];
var request = $http.get('/live-ticker');
request.success(function(ticker) {
console.log(ticker); //only logging data once
$scope.liveTicker = ticker;
});
request.error(function(err) {
console.log('Error: ' + err);
});
});
How would get live updates pushed to client?
Thank you
you need to push data from the server periodically.
to get these "live updates" on the client side, a plain ajax call is not enough,
you need a realtime communication.
You should use websoket even here, with socket.io and angular socket.io for example you can handle this communication easily

SocketIO, can't send emit data from client

I'm having the most odd problem trying to send data from a client browser to my node server using SocketIO. Sending from server to client works just fine, but the other way around I get an undefined error. Here's a quick bit of what it looks like, super simple.
Node Server (app.js)
io.on("connection", function(socket) {
socket.on("pageReady", function(data) {
console.log('pageReady called');
console.log(data);
return socket.emit('newline', '###SOCKET STARTED###');
});
socket.on("disconnect", function() {
return console.log('disconnected');
});
});
Browser (client.js)
var socket;
socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.emit("pageReady", "test");
Super simple, right? Nothing special. When I emit from server, works fine, however when the client calls "pageReady". node responds with this.
/Volumes/HOME/Users/user/git/sockettest/app.js:89
console.log(data);
^
ReferenceError: data is not defined
Data should be returning "test", but isn't. What am I doing wrong?
Your client should listen for the socket connection before attempting to emit to it:
var socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.on("connect", function() {
socket.emit("pageReady", "test");
});

WebSocket connection established, but can't receive messages

I've written a short WebSocket example server in PHP yesterday. When the client connects to the server, the server reads the client Handshake and sends the server Handshake back with the appropriate key. onopen() of the client gets fired and the server and client seem to be connected.
My problem is: The server can't receive client messages and the client can't receive server messages. onmessage() wasn't triggered once and socket_select() never gives back the client that sent the message on server side.
function connect() {
try {
var webSocketURL = "ws://" + serverAddress + ":" + serverPort;
socket = new WebSocket(webSocketURL);
socket.onopen = function() {
log("Connected! (" + this.readyState + ")");
}
socket.onclose = function() {
log("Closed! (" + this.readyState + ")");
socket.close();
}
socket.onerror = function(error) {
log("Error: " + error.data);
socket.close();
}
socket.onmessage = function(message) {
log("Message from server: " + message.data);
}
}
catch (e) {
alert("Error: " + e);
}
}
The server code is a bit longer, but you can find it here.
Can anyone tell me what's wrong there? Is the handshake incorrect?
Client output:
Connected! (1)
Message to server: 0USERchannel
Server output.
Help is much appreciated, thank you.
On client side, enshure your socket variable is global.

Read raw http message in Nodejs

I'm sending an http request using the http.request function, and I would like to read the whole http response like text; that is, the raw http protocol text. Is it possible? I've written the below code but it's not working.
// Set up the request
console.log('Sending request');
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
console.log('Response statusCode: ' + res.statusCode);
// res.on('data', function (chunk) {
// console.log('Response: ' + chunk);
// });
// res.on('end', function() {});
});
post_req.on('socket', function (socket) {
var response = "";
socket.on('data', function(chunk){
console.log(chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
If you want access to the raw http message, I'd suggest using the net module instead, and writing the request yourself. Something like this for a simple GET request:
var net = require('net');
var host = 'stackoverflow.com',
port = 80,
socket = net.connect(port, host, function() {
var request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n",
rawResponse = "";
// send http request:
socket.end(request);
// assume utf-8 encoding:
socket.setEncoding('utf-8');
// collect raw http message:
socket.on('data', function(chunk) {
rawResponse += chunk;
});
socket.on('end', function(){
console.log(rawResponse);
});
});
For a POST request sending application/x-www-form-urlencoded data, you could write the request using something like:
function writePOSTRequest (data, host, path) {
return "POST " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + Buffer.byteLength(data) + "\r\n\r\n" +
data + "\r\n\r\n";
}
var data = "name1=value1&name2=value2",
request = writePOSTRequest(data, host, "/path/to/resource");
where I'm using Buffer.byteLength because Content-Length requires the length in bytes, not in characters. Also, remember that data must be URL encoded.
If you don't know much about the format of HTTP messages, then this is a decent place to start:
http://jmarshall.com/easy/http/
Also, if you don't know what the encoding of the response will be then you'll have to parse the headers first to find out, but UTF-8 is by far the most common so it's a pretty safe bet.
Streams2 and Streams1 not always able to inter-operate well, see "problem: streams1 and streams2 duality" in this video.
I tried to listen data at a bit lower level than streams and this code prints raw http response with headers for me:
var http = require('http');
var raw = '';
console.log('Sending request');
var req = http.request({host: 'stackoverflow.com'}, function(res) {
watch(res, 'res');
res.on('end', function() {
console.log(raw);
});
res.on('data', function(data) {
// if we don't attach 'data' handler here 'end' is not called
});
});
req.on('socket', function (socket) {
socket.resume();
var oldOndata = socket.ondata;
socket.ondata = function(buf, start, end) {
raw += buf.slice(start, end).toString();
oldOndata.call(socket, buf, start, end);
};
});
req.end();
Assuming these kind of tools are allowed in your environment, you could run up an HTTP debug proxy such as Fiddler http://www.fiddler2.com/, which enables you to inspect the HTTP calls and responses.

Node.js calling a function from script to update UI

Here is my webserver:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('hello\n');
socket.write('world\n');
//RECEIVE PACKET ON SOCKET
socket.on('data', function(data) {
//socket.write(data);
//console.log(data);
testSocketData(data)
});
});
server.listen(8000);
And the method testSocketData(data) is located in file update_ui.js and does the following:
function testSocketData(test) {
$('#p1').text(test)
}
Where #p1 refers to the id of a paragraph element in my main.html. I know that my socket is working, however I get:
ReferenceError: testSocketData is not defined.
How can I simply pass off the data received from my node.js server to the rest of my web application?
You must move that method(with socket.on('data') as well) from the server to the client side. When you receive a message via socket, the p1 element will update its text too.
On the server you will still need to have a socket.on('data') to receive the messages from the client.
Edit:
Here is some code, a little bit changed from my comment below.
On server:
function computeSomeResults(data) {
// your logic here
}
socket.on('servermsg', function(data) {
var result = computeSomeResults(data);
socket.emit('clientmsg', result);
});
On client:
function testSocketData(test) {
$('#p1').text(test);
}
socket.on('clientmsg', function(data) {
testSocketData(data);
// emit something maybe?
}
Eventually, you may want to send something to the server:
$('#p1').on('click', function(){
socket.emit('servermsg', $(this).text());
});

Categories

Resources