Why does my Node.js server hang with this small script? - javascript

Edit: Answered below
New to Node.js here, I really want to know why this script hangs forever when I'm attempting to connect to the created server.
I've had this happen often enough when I'm trying to create a server and I'm not sure why, as it seems to happen with very similar code:
Node script:
var http = require("http");
var file = require("fs");
var server = http.createServer(function(request, response)
{
file.readFile("chat.html", "UTF-8", function(error, content)
{
if(error) { console.error(error.stack); response.end(); }
response.writeHead(200, {"content-type" : "text/html"});
response.end(content);
});
}).listen(1994, function(){console.log("Listening");});
var websocket = require("socket.io").listen(server);
websocket.sockets.on("connection", function(socket)
{
socket.emit("message", {"message" : "Hello World"});
});
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Chat</title>
<meta charset="utf-8">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = websocket.connect();
socket.on("message", function(message)
{
console.log(message);
});
</script>
</head>
<body>
<div>Socket file.</div>
</body>
</html>
If there is an error then it should end the response and if there isn't it should end the response, or does it have something to do with the web socket?

Try changing how you are invoking socket.io:
var websocket = require('socket.io')(server);
websocket.on('connection', doStuff);
This example follows directly from the docs on GitHub.

The problem was with websocket.connect(). Socket.io uses io as a global object in the front end, not websocket. So it should have been io.connect().

Related

How to send variables from Node.js to Socket.io and display on local webpage?

I'm working on a project where my job is to use Node.js and Socket.io to read a text file (contain 3 real time readings) and got the data in 3 variables, then send them to Socket.io and get them displayed on the website continuously without having to refresh it. I ran my codes, it did not give any errors, but it did not display anything on the website either. So I don't know what is wrong in my code. I need help with passing variables from Node.js to Socket.io and get them displayed on the my web page.
This is my server file:
var http = require('http').createServer(handler); //require http server, and cr$
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the htt$
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/index.html', function(err, data) { //read file inde$
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {
setInterval(function(){
var array = fs.readFileSync('report.txt').toString().split("\n");
var volt = (array[0]);
var power = (array[1]);
var temp = (array[2]);
socket.emit('volt',{'volt': volt});
socket.emit('power',{'power': power});
socket.emit('temp',{'temp': temp});
}, 1000);
});
index.html file :
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://10.117.230.219:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
socket.on('power', function (data) {
$('#power').text(data.power);
socket.on('temp', function (data) {
$('#temp').text(data.temp);
});
</script>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
You are missing some tags on your HTML page including HTML and head. You are also missing a closing )} for each socket.on(...) call in your script. This is what it should look like:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
})
socket.on('power', function (data) {
$('#power').text(data.power);
})
socket.on('temp', function (data) {
$('#temp').text(data.temp);
})
</script>
</head>
<body>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
</html>
This should do it.

I don't see on client in real time the value of json file with node js

I see this example on a precedent question on this link how to display a realtime variable in nodejs in HTML and i dont't see in real time the value of json file on client
despite the answer is defined correctly.
Moreover in the bash i launch the command node --inspect socketProva.js (socketProva.js is the name of my server file) and i see in the page of inspect this message "WebSockets request was expected". The strange thing is that the server show correctly in real time the data of json file but the communication with client it does not seem to happen.
Thanks for the answers and excuse for my bad english.
socketProva.js and index.html
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', obj);
obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
socket.emit('update-value', obj); // Emit on the opened socket.
incremental++;
}, 1000);
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="messages"></p>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
JSON File: prova.json
{
"football":{
"id": 1,
"home": "Liverpool",
"away": "Chelsea",
"score": "1-0",
"last scorer":"Gerrard"
}
}
If the prova.json don't change during time, there is no need to read it using fs.readFileSync. You can require it.
var obj = require('prova.json');
The full example is shown below: (remember I changed the client socket.io.js version)
server:
var io = require('socket.io')();
var data = require('./data.json')
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
setInterval(function () {
data.value = Math.random();
socket.emit('update-value', data);
console.log('message sent to the clients');
}, 1000);
});
io.listen(8080);
client:
<!DOCTYPE html>
<html>
<head>
<!-- this changed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="incremental"></div>
<script>
var socket = io('http://localhost:8080');
socket.on('update-value', function (data) {
console.log('received new value', data);
var $div = $('<div>');
$div.text(data.value)
$('#incremental').append($div);
});
</script>
</body>
</html>
And data.json:
{
"value": 1
}

node js simple chat app delay on event trigger

i prepared a simple chat system while practicing node.js. but theres a problem while sending messages. quite a good amount of delay taking place while sending messages and i couldnt figure out why. can anyone help me how to improve attached code ?
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
io.on('connection', function(client) {
client.on('messageSend', function(data) {
client.broadcast.emit('messageRecieve', data);
});
});
http.listen(9090, function() {
console.log('Listening on port 9090');
io.on('connect', function(socket) {
console.log("Connection established : " + socket.client.conn.remoteAddress);
})
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket Test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
function messageSend() {
var message = document.getElementById("messageInput").value;
console.log(message);
var ul = document.getElementById("messageNode");
var li = document.createElement("li");
li.appendChild(document.createTextNode(message));
li.setAttribute("style", "font-style : italic; color : red;");
ul.appendChild(li);
socket.emit('messageSend', message);
}
socket.on('messageRecieve', function(data) {
var message = data;
var ul = document.getElementById("messageNode");
var li = document.createElement("li");
li.appendChild(document.createTextNode(message));
ul.appendChild(li);
console.log(message);
});
</script>
</head>
<body>
<input id="messageInput" type="text"> <button onclick="messageSend()">Send</button><br>
<ul id="messageNode">
</ul>
</body>
</html>
the official socket.io example sends the message to everyone, including yourself
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
You sent to everyone except yourself (which is the most accurate method)
io.on('connection', function(client) {
client.on('messageSend', function(data) {
client.broadcast.emit('messageRecieve', data);
});
});
The reason for your slowdown is probably becouse your browser puts your out-of-focus tabs in a sort of sleep mode, which makes it update much less frequently... If you compare your code vs socket.io's code between computer and phone via lan. I would guess the speed for your server-sent message would be the same
Right now you are basically competing versus socket.io's "optimistic updates". It pushes the message to your client directly without waiting for the server, which your own code does. As well as browser out-of-focus low priority mode

Sockets - No data is shown on the client site

I want to send data via socket.io to my client via nodejs.
The data I am receiving are from pusher.
I am using an express backend and loading my server like that.
#!/usr/bin/env node
var debug = require('debug')('testApp');
var app = require('../app');
var Pusher = require('pusher-client');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
io.sockets.on("connection", function (socket) {
// This will run when a client is connected
// This is a listener to the signal "something"
socket.on("data", function (data) {
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
console.log(data);
});
});
// This is a signal emitter called "something else"
socket.emit("something else", {hello: "Hello, you are connected"});
});
On my client I am running the following script:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
My socket.js file:
var socket = io.connect(window.location.hostname);
socket.on('data', function(data) {
var total = data.total;
//print data to console
console.log(data);
});
My problem is that nothing gets shown in the console in my webbrowser, even though the data is coming in at my nodejs application.
Any recommendation what I am doing wrong?
I appreciate your replies!
I do believe the problem is when you use: socket.emit("something else", {hello: "Hello, you are connected"});
but have this in client-side: socket.on('data', function(data) {.
When you emit, you use the channel "something else", but on the client-side you are checking on the channel "data".
So on client-side you should be having socket.on('something else', function(data){.
Hope I helped. There isn't much info I could find on sockets.io, so I do not know if there is a preexisting channel called 'data'. Do enlighten me if so :)

connection refused node js

Helle every body i desired to test sockets,when i'm connected a alert should appear, it work on the computer where Node js is in installed but not in the other computer.
The error :
Failed to load resource: net::ERR_CONNECTION_REFUSED
http://xxx.xxx.xxx.xxx:8080/socket.io/socket.io.js Uncaught
ReferenceError: io is not defined
the code :
server:
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html'});
fs.readFile('./index.html',function(err,content){
res.end(content);
});
}).listen(8080);
io = io.listen(server)
io.sockets.on('connection',function(client){
client.emit('connecte');
});
client :
<html>
<meta charset='utf-8'/>
<head>
<title>my first page</title>
<script src="http://localhost:8080/socket.io/socket.io.js" ></script>
</head>
<body>
<h1>It work</h1>
</body>
<script>
var socket;
socket = io.connect('http://localhost:8080');
socket.on('connecte', function(){
alert('You are connected');
});
</script>
</html>
sorry for the language english is not my first language i try to learn.
Thanks
The Socket.IO docs shows how to use Socket.IO with the built-in http server. Comparing that example and your code you can see you're not using io quite right. Try something like this:
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./index.html', function(err, content) {
res.end(content);
});
});
io = io(server);
server.listen(8080);
io.on('connection', function(client) {
client.emit('connected');
});
Also on an unrelated note, you could pipe() the html file to the client instead of buffering the entire file first:
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('index.html').pipe(res);

Categories