I was working on nodejs executing python scripts using spawn and socket.io methods. I am getting output on the console. but I am not able to display it on the browser. It is showing error.I have pasted the error below. Can any one please help me in solving this problem. I have got this example from this stackoverflow
Here i am pasting my code: sample.py
import random, time
for x in range(10):
print(str(random.randint(23,28))+" C")
time.sleep(random.uniform(0.4,5))
index.js
var express = require("express");
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var spawn = require('child_process').spawn;
var http = require('http').Server(app);
var io = require('socket.io')(http);
var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/showtemp',function(req,res){
var pathtoScript = spawn('python', ["../External_scripts/sample.py"]);
pathtoScript.stdout.on('data', function (output) {
var val = String(output);
console.log(val);
io.sockets.emit('response', { data: val});
});
})
var server = app.listen(8082,'0.0.0.0', function () {
var port = server.address().port
console.log("App is listening at %s", port)
});
And index.html page
<!doctype html>
<html>
<head>
<title>Live temperature</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="liveTemp">Loading...</div>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
socket.on('response',function(msg){
console.log("msg");
$('#liveTemp').html(msg.data);
})
});
</script>
</body>
</html>
I am getting this error
GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)
GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)
You haven't started a web server anywhere or hooked socket.io to it. There are several different ways to do this, but here's one that works:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
Note: You must see a server.listen() (or equivalent) somewhere. And, you need to pass the server to socket.io so it can hook into it.
You can also do this where you don't directly need to load the http module yourself:
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);
socket.io documentation for several different options here.
Related
this issue has been boggling my mind for days. There's nothing noticable to me that I have done, but my node port produces an insecure socket, while my site itself is completely secure (ssl). So mathtutortime.com is secure, but this is the error I get when I go to https://www.mathtutortime.com/account/get_tutoring/lobby.php:
I tried reinstalling my ssl certificate, as well as ensuring my ssl certificate isn't expired, but to no avail. I have also gone to the actual part of my site in node having this issue, and it indeed is not secure :( Even though mathtutortime.com IS.
Here's my code for lobby.php:
gather data for site, then create a post request
<script src="https://mathtutortime.com:3001/socket.io/socket.io.js"></script>
<script>
var BACKEND_URL = 'https://mathtutortime.com:3001';
var SESH_END_INCORRECT = 'https://mathtutortime.com/account/get_tutoring/done_incorrect';
var SESH_END_CORRECT = 'https://mathtutortime.com/account/get_tutoring/done_correct';
var name = "<?php echo $_SESSION["username"]?>";
var pass = "<?php echo $_SESSION["password"]?>";
var time = 0;
var role = 'tutor';
$.post(`${BACKEND_URL}/requestWhiteboard`, { name, time, role, pass }, function(res){
window.location.href = `${BACKEND_URL}/whiteboards/${res.whiteboardId}`;
</script>
And here's my server in node:
var fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var all;
var options = {
key: fs.readFileSync('./privatekey.key'),
cert: fs.readFileSync('./certificate.crt'),
requestCert: false,
rejectUnauthorized: false
};
const chat_port = 3001;
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
var server = require('https').createServer(options, app);
require('https').globalAgent.options.rejectUnauthorized = false;
var io = require('socket.io').listen(server);
app.post('/requestWhiteboard', function(req, res){
...
}
app.get('/socket.io.js', function(req, res){
res.sendFile(__dirname + '/socket.io.js');
});
var host = '45.79.111.96';
server.listen(chat_port, host, function(){
console.log('listening on *' + chat_port);
});
Also, socket.io.js is in my directory (referenced in an app.get below)
Thanks for any ideas!
at the moment I have an app.js file and a server.js file. The server runs fine when I run 'node app.js' in CMD but I'm trying to put everything in the server.js file.
App.js:
var Server = require('./server.js').Server;
var server = new Server();
server.initialise(8080);
Server.js:
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var app = express();
exports.Server = Server = function() {
this.userId = 1;
};
Server.prototype.initialise = function(port) {
this.server = http.createServer(app);
app.use(express.static('public'));
this.server.listen(port);
this.startSockets();
this.em = new events();
console.log('Server running on port: ' + port);
};
So I've tried moving the last 2 lines of app.js to the server but I'm getting the error that Server isnt a constructer. I've tried
var Server = this;
I've also tried
this.initialise(8080);
Nothing seems to work
I have a few questions about configuring socket.io for my node.js application.
When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?
Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?
const numbers = '1234'
function asd(req,res,next) {
socket.emit('a')
}
module.exports = {
asd
}
For configuring client-side socket.io, I added this line:
var socket = io.connect('https://mydomain')
Do I need to say 'mydomain:port' or is 'mydomain' enough?
This is how you use socket.io
var http = require('http');
var express = require('express');
var path = require('path');
var app = http.createServer();
var io = require('socket.io')(app);
var port = 8081;
io.on('connection', function(socket){
socket.on('event1', function (data) {
console.log(data);
socket.emit('event2', { msg: 'delivered' });
});
});
app.listen(port);
Answer to your second question
Yes, you will need to specify the port you are using
<script src="socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect('https://mydomain:8081')
socket.on('your_event',function() {
console.log('your_event receivid from the server');
});
</script>
Here socket will connect to port 8081
This is a simple server side code
var http = require('http');
var io = require('socket.io');
var port = 8081;
// Start the server at port 8081
var server = http.createServer();
server.listen(port);
var socket = io.listen(server);
// example listener
socket.on('event_2', function(client){
console.log('event_2 received');
});
// example emitter
socket.emit('event_1', { hello: 'world' });
This is what I have tried so far.
socket-server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var config = require('./config2.js');
app.get('/', function(req, res){
res.sendfile('socket-client.html');
});
io.on("connection", function (socket) {
var mapRes = {width : 720, height: 1040};
socket.emit("mapRes", mapRes);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Relevent scripts from socket-client.html
var socket = io();
window.onload = function() {
var paper = new Raphael(document.getElementById('canvas'), canvas_width, canvas_height);
socket.on('mapRes', function(message){
var mapRes = message;
var mapImg = paper.image("http://localhost/home/username/Desktop/map.png",0,0,mapRes.width,mapRes.height);
});
}
Here, "canvas" just an id of the tag where the image is supposed to be loaded
Although the console showed GET http://localhost/home/username/Desktop/map.png [0ms], the image is not loaded.
both the image and the codes (socket-server.js & socket-client.html) are in the same folder as the map.png.The complete path to folder is /home/username/Desktop. Can someone enlighten me on where I got it wrong?
You could create a folder under the same folder as the script files and name it as "public" (or whatever you'd like).
On your socket-server.js,
var express = require('express');
var app = express();
app.use(express.static('public')); //let express access your "public" folder.
On your client.html,
var mapImg = paper.image("./map.png",x,y,width,height);
Paper will try to load your image from your "public" folder.
FYI, "http:" won't be able to access your local files(from local HDD) for security reasons.
I have set up a server in node.js using socket.io and epxress.
When I set it up as shown below, it works like charm (now it's listening on 8080).
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
But I need it to listen to different port, and if I try eg. 8000
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(8000);
I get the following error:
GET http://10.0.33.34:8080/socket.io/socket.io.js 404 (Not Found). Can anybody please help me?
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var port = 8000;
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
Above code is not tested but most likely it will not fail. Pass port value to listen method of http.createServer(app).
var express = require('express')
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//Code needs to be in this order
and check in the script that the port is 8000
<script src=""></script>
Do you include the script in you html ?
Maybe change the include to the port 8000.
<script src="http://10.0.33.34:8000/socket.io/"></script>