Failed to load resource - Socket.IO - javascript

I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);
//file doesn't exist
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
//handles serving file data
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//cache static files to memory
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3001, function() {
console.log("Server listening on port 3001.");
});
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Chat</title>
<meta name="description" content="An interactive chat application using websockets.">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send'/>
<div id='help'>
Chat commands:
<ul>
<li>Change nickname: <code>/nick [username]</code></li>
<li>Join/create room: <code>/join [room name]</code></li>
</ul>
</div>
</form>
</div>
<script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
<script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/javascripts/chat.js" type="text/javascript"></script>
<script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>
Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:
Error 404: resource not found.
I right-clicked and inspected element from my Chrome browser and got this two messages:
Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"
Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"
This is line 26 from my chat_ui.js file:
var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {
var chatApp = new Chat(socket);
socket.on('nameResult', function(result) {
var message;
if (result.success) {
message = 'You are now known as ' + result.name + '.';
} else {
message = result.message;
}
$('#messages').append(divSystemContentElement(message));
});
socket.on('joinResult', function(result) {
$('#room').text(result.room);
$('#messages').append(divSystemContentElement('Room changed.'));
});
socket.on('message', function (message) {
var newElement = $('<div></div>').text(message.text);
$('#messages').append(newElement);
});
socket.on('rooms', function(rooms) {
$('#room-list').empty();
for(var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
$('#room-list').append(divEscapedContentElement(room));
}
}
$('#room-list div').click(function() {
chatApp.processCommand('/join ' + $(this).text());
$('#send-message').focus();
});
});
setInterval(function() {
socket.emit('rooms');
}, 1000);
$('#send-message').focus();
$('#send-form').submit(function() {
processUserInput(chatApp, socket);
return false;
});
})
I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:
to
...as i thought this was the problem, but it is still giving me the same error.
Please how do i resolve this?
(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)

Try this:
<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>
<script type="text/javascript">
var socket = io.connect('http://localhost:3001');
socket.on('connect',function(){
console.log("connect");
});
</script>
It must help you.

The line chatServer.listen(server); should be after you run your server.
chartServer is listening to the server but that one is not running yet.
Try to move this line:
chatServer.listen(server);
to the end of your script server.js

Related

Client Recieves Data From Server

So I have a Raspberry Pi 4 and im trying to receive data from a JSON file and display it on a text element on my website. sorry if im totally wrong, it's my second day with a Raspberry Pi. I have done basic things like turn an LED on, thanks to w3schools. Im trying to make a bot hosting tool thing for myself, where it will display amount hosted on a TV
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
</head>
<body>
<div class="container">
<h1>Bots Hosted:</h1>
<h2 id="bot-qty">0</h2>
</div>
</body>
<script>
var socket = io();
window.addEventListener("load", function() {
var bot_count = document.getElementById("bot-qty");
var times_ran = 0;
const interval = setInterval(function() {
socket.emit("request-count", times_ran);
times_ran++;
}, 20000);
})
socket.on('request-count', function(data) {
document.getElementById("bot-qty").innerText = data;
})
</script>
</html>
webserver.js:
var http = require('http').createServer(handler);
var fs = require('fs');
var io = require('socket.io')(http);
http.listen(1337);
function handler(req, res) {
fs.readFile(__dirname + '/public/index.html', function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
io.sockets.on('connection', function(socket) {
socket.on('request-count', function(data) {
var bot_count = JSON.parse(fs.readFileSync("config.json", "utf8"));
console.log(bot_count);
socket.emit('request-count', bot_count);
});
});
In console, it says
GET <long_url_here> net::ERR_NAME_NOT_RESOLVER
In the index.html you initialize a new Socket instance by writing
var socket = io();
You don't provide any url, so the socket.io-client will use the default window.location as can be seen here. This might be a problem, so try to set a specific url, e. g.
var socket = io('http://localhost');
or (also specifying the port)
var socket = io('http://localhost:1337');
Also try to make sure that you run your webserver.js with node webserver.js prior to open the website.
Also see this discussion on GitHub.

Socket IO randomly send number when idle

i am facing an issue about socket io random send number when idle..
chat.js:
$(document).ready(function(){
var socket = io();
socket.emit("handshaking","");
$('.input').keypress(function (e) {
if (e.which == 13) {
var msg = $('.input').val();
if(msg !=""){
socket.emit("sendMessage",msg);
$('.chat-box').append("<p class='msgSend'>"+msg+"</p><br>");
$('.input').val('');
}
}
});
//If handshaking success, print a message to chat box
socket.on("pong", function(msg){
$('.chat-box').append("<p class='systemMsg'>" + msg + "</p><br>");
});
//Player message
socket.on("getMessage",function(msg){
$('.chat-box').append("<p class='msgReceive'>"+msg+"</p><br>");
});
});
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var path = require('path');
var mime = require('mime');
var fs = require('fs');
var cache = {};
app.listen(80,function(){
console.log("Listening to port 80.");
});
function send404(res){
res.writeHead(404,{'content-type': 'text/plain'});
res.write('Error 404: resource not found.');
res.end();
}
function sendFile(res, filePath, contents){
res.writeHead(200,{"content-type": mime.getType(path.basename(filePath))});
res.end(contents);
}
function serverStatic(res, cache, path){
if(cache[path]) {
sendFile(res, path, cache[path]);
} else {
fs.exists(path, function(exists) {
if(exists) {
fs.readFile(path, function(err,data) {
if(err) {
send404(res);
} else {
cache[path] = data;
sendFile(res,path,data);
}
});
} else {
send404(res);
}
});
}
}
function handler (req, res) {
var filePath;
if(req.url == '/'){
filePath = 'public/index.html';
console.log(filePath);
} else {
filePath = 'public' + req.url;
console.log(filePath);
}
var path = './' + filePath;
serverStatic(res, cache, path);
}
io.on('connection', function (socket) {
socket.on('disconnect', function(){
console.log('user disconnected');
socket.broadcast.emit("pong","A user has leave the room.");
});
socket.on("handshaking",function(msg){
console.log("A user is joined.");
socket.broadcast.emit("pong", "A user has join the room.");
});
socket.on("sendMessage",function(msg){
socket.broadcast.emit("getMessage",msg);
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat System</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
<div class="chat-area">
<div class="chat-box"></div>
<input class="input" style="width:100%;" placeholder="Type something"> <!--<button style="">SEND</button>-->
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.slim.js"></script>
<script src="/js/chat.js" type="text/javascript"></script>
</body>
</html>
I am not sure what's wrong with these code but i am sure that all is working except it will auto send some random number when i idle the browser (the page is still on).
Can someone help me take a look on this issue?
Thank you!

Style and javascript files not applied to page that is serving HTML in Node.js

I am currently serving my HTML page which references style.css and index.js, however, these files are not being applied to the HTML page even though I explicitly stated to include them if they are requested by 'req'?
My HTML (to show inclusions):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test site</title>
<link rel="stylesheet" href="/style.css" media="screen">
<script src="/index.js" charset="utf-8" defer></script>
.
.
.
My server.js code:
var PORT = 3000;
var http = require('http');
var fs = require('fs');
var path = require('path');
//cache the files
var index = fs.readFileSync('public/index.html', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var style = fs.readFileSync('public/style.css', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var indexJS = fs.readFileSync('public/index.js', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
function requestHandler(req, res){
res.setHeader('Content-Type', 'text/html');
res.statusCode = 200
res.write(index);
if(req.url === '/style.css'){
res.write(style);
}
if(req.url === '/index.js'){
res.write(indexJS);
}
res.end();
}
//use 3000 by default if PORT is not defined
if(!(typeof PORT !== 'undefined') || PORT === null){
http.createServer(requestHandler).listen(PORT);
}
else{
http.createServer(requestHandler).listen(3000);
}
Looks like you have the right idea but there are a couple things to note in the server code.
Setting the Content Type header tells the web browser how to interpret the file it is receiving. Your server code always sets it to 'text/html' where it should be set to 'text/css' for css, and 'text/javascript' for your js files.
res.write will append the file contents to the response. Since res.write(index) is being executed on every request, your HTML is being sent before the css/js within the same file. Try using a conditional for HTML like you are doing for CSS/JS like
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}

socket.io 404 cant connect with socket.io server

I have webrtc / socket.io / nodejs running on a server, everything works fine when i go to the https://domain.com:8080 to test a video conference.
But i want the script to run in my webserver /public_html/
But i dont know why it is not connecting to the 8080 server.
"socket.io.js GET https://domain.com/socket.io/?EIO=3&transport=polling&t=LPgZs2K 404 (Not Found)"
my server (server.js)
// Load required modules
var https = require("https"); // http server core module
var express = require("express"); // web framework external module
var serveStatic = require('serve-static'); // serve static files
var socketIo = require("socket.io"); // web socket external module
var easyrtc = require("../");
const fs = require('fs'); // EasyRTC external module
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// Set process name
process.title = "node-easyrtc";
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
// Start Express http server on port 8080
var webServer = https.createServer(options, app).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = socketIo.listen(webServer, {"log level":1});
easyrtc.setOption("logLevel", "debug");
// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj){
if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) {
callback(err, connectionObj);
return;
}
connectionObj.setField("credential", msg.msgData.credential, {"isShared":false});
console.log("["+easyrtcid+"] Credential saved!", connectionObj.getFieldValueSync("credential"));
callback(err, connectionObj);
});
});
// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
console.log("["+connectionObj.getEasyrtcid()+"] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});
// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer, null, function(err, rtcRef) {
console.log("Initiated");
rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
console.log("roomCreate fired! Trying to create: " + roomName);
appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
});
});
//listen on port 8080
webServer.listen(8080, function () {
console.log('listening on http://localhost:8080');
});
my html file on de WEB server. structure like this https://domain.com/test.html
<!DOCTYPE html>
<html>
<head>
<title>EasyRTC Demo:EasyRTC Demo: Video+Audio HD 720</title>
<link rel="stylesheet" type="text/css" href="/easyrtc/easyrtc.css" />
<script src="js/socket.io.js"></script>
<script type="text/javascript" src="js/easyrtc.js"></script>
<script type="text/javascript" src="js/video.js"></script>
<script>
var selfEasyrtcid = "";
function connect() {
easyrtc.setVideoDims(1280,720);
easyrtc.enableDebug(false);
easyrtc.setRoomOccupantListener(convertListToButtons);
easyrtc.easyApp("easyrtc.videoChatHd", "selfVideo", ["callerVideo"], loginSuccess, loginFailure);
}
function clearConnectList() {
var otherClientDiv = document.getElementById("otherClients");
while (otherClientDiv.hasChildNodes()) {
otherClientDiv.removeChild(otherClientDiv.lastChild);
}
}
function convertListToButtons (roomName, data, isPrimary) {
clearConnectList();
var otherClientDiv = document.getElementById("otherClients");
for(var easyrtcid in data) {
var button = document.createElement("button");
button.onclick = function(easyrtcid) {
return function() {
performCall(easyrtcid);
};
}(easyrtcid);
var label = document.createTextNode(easyrtc.idToName(easyrtcid));
button.appendChild(label);
button.className = "callbutton";
otherClientDiv.appendChild(button);
}
}
function performCall(otherEasyrtcid) {
easyrtc.hangupAll();
var acceptedCB = function(accepted, caller) {
if( !accepted ) {
easyrtc.showError("CALL-REJECTED", "Sorry, your call to " + easyrtc.idToName(caller) + " was rejected");
}
};
var successCB = function() {};
var failureCB = function() {};
easyrtc.call(otherEasyrtcid, successCB, failureCB, acceptedCB);
}
function loginSuccess(easyrtcid) {
selfEasyrtcid = easyrtcid;
document.getElementById("iam").innerHTML = "I am " + easyrtc.cleanId(easyrtcid);
}
function loginFailure(errorCode, message) {
easyrtc.showError(errorCode, message);
}
// Sets calls so they are automatically accepted (this is default behaviour)
easyrtc.setAcceptChecker(function(caller, cb) {
cb(true);
} );
</script>
</head>
<body onload="connect();">
<h1>EasyRTC Demo: Video+Audio HD 720p</h1>
<div id="demoContainer">
<div>
Note: your own image will show up postage stamp sized, while the other party"s video will be shown in high-definition (1280x720). Note: not all webcams are seen by WebRTC as providing high-definition video; the fallback is to use standard definition (640x480).
</div>
<div id="connectControls">
<div id="iam">Not yet connected...</div>
<br />
<strong>Connected users:</strong>
<div id="otherClients"></div>
</div>
<div id="videos">
<div style="position:relative;float:left;" width="1282" height="722">
<video autoplay="autoplay" id="callerVideo"></video>
<video class="easyrtcMirror" autoplay="autoplay" id="selfVideo" muted="true" volume="0" ></video>
</div>
<!-- each caller video needs to be in it"s own div so it"s close button can be positioned correctly -->
</div>
</div>
</body>
</html>
Socket.io.js: http://81.171.38.245/js/socket.io.js

Failed to load resource error handling

I have been doing some nodeJS testing with socket.io and have noticed when i don't run the nodeJS my client errors.
When nodeJS is not running I get this error in my client console.log:
Failed to load resource socket.io/socket.io.js
My client code is like this:
<script src = "socket.io/socket.io.js" > < /script>
<script>
window.onload = function(){
if(typeof io != 'undefined'){
socketio = io.connect("[hidden]:[hidden]");
socketio.on('error', function(err) {
if(err === 'handshake error') {
console.log('handshake error', err);
} else {
console.log('io error', err);
}
});
} else {
console.log('IO not started?');
}
}
</scirpt>
So i'm wondering - whats the best way to preiodically check when nodeJS has started up ?
Not an elegant solution, but this should solve your problem -
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
var connected = 0;
var socket;
var timer = setInterval(function(){
loadScript();
},1000);
function loadScript() {
$.getScript("http://<ip>:<port>/socket.io/socket.io.js")
.done(function( script, textStatus ) {
//console.log( textStatus );
if(!connected) {
socket = io.connect('http://<ip>:<port>');
connected = 1;
clearInterval(timer);
}
});
}
});
</script>
you can send a request to your nodejs server,if server return 500. nodejs is stopping now.
<script>
var socket = io.connect();
socket.on('connect', function(){
console.log('connected');
//do Something...
})
</script>
if you want to check socket.io.js whether it has finished loading, you can try to use Require.js
http://requirejs.org/

Categories

Resources