socket.io 404 cant connect with socket.io server - javascript

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

Related

Data sent to my node.js server isn't being sent back to the client

I'm still relatively new to node.js, so I decided to practice with a simple program.
I made this program to test the connectivity between the client and the server using node.js, express and socket.io.
This is my server.js
// Create an http server with Node's HTTP module.
const http = require('http');
// Create a new Express application
const express = require('express');
const app = express();
const clientPath = `${__dirname}/../client`;
console.log(`Serving static from ${clientPath}`);
app.use(express.static(clientPath));
const socketio = require('socket.io');
// Pass the http server the Express application
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', function (socket) {
console.log("There's been a connection");
socket.on("console output", function (input) {
console.log(input)
});
socket.on("text alter", function(data){
var display = "'" + data + "' An interesting set of characters";
io.sockets.emit("display string", display);
})
})
//Listen on port 8080
server.listen(8080, function () {
console.log("Listening on port 8080");
})
This is my index.js
const socket = io();
let players = [];
function serverOutput(){
socket.emit("console output", "You suck at programming");
}
function serverAlter(){
const alterInput = document.querySelector('#userinput1').value;
socket.emit("text alter", alterInput);
}
socket.on("display string", function(){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
outputArea.appendChild(fullLine);
})
Lastly my index.html
<html lang="en">
<head>
<title>Home</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="main-menu" class="page-templates">
<h3>Part 1: Press the button to see the server send a message</h3>
<button onclick="serverOutput()">Server message</button>
<br>
<h3>Part 2: Type in a string, and the server will add to it</h3>
<input type="text" id="userinput1">
<div id="outputspace1">
</div>
<button onclick="serverAlter()">Create sentence</button>
<script src="/socket.io/socket.io.js"></script>
<script src="src/index.js"></script>
</body>
</html>
From how the code runs, the server is able to pick up the data from the client, but when I try to change the data and send it back, the paragraph that is meant to be outputting the string has no data. I have a feeling I implemented the "io.sockets.emit()" incorrectly, but please if you guys can enlighten me, I would be so grateful.
In the client code, when you add data to your #outputspace1 element with this:
socket.on("display string", function(){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
outputArea.appendChild(fullLine);
});
All you are doing there is adding an empty <p></p> element to #outputspace1. Instead, you need to capture the data being sent back to you by declaring the right incoming function parameter on your .on() event handler and then you need to add that data to the p element you created like this:
socket.on("display string", function(newText){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
fullLine.innerHTML = newText;
outputArea.appendChild(fullLine);
});

How to download file from Cloud Storage [Firebase Hosting]

I would like to make a web app using Firebase Hosting.
make audio file using Cloud text to speech API
upload that audio file to Cloud Storage
download that audio file from Cloud Storage to a web browser
I passed step 1 and 2, but have a trouble with step 3.
I followed this turorial.
https://firebase.google.com/docs/storage/web/download-files
I deployed my Firebase project and tested my app. I could upload audio file to Cloud Storage, but I couldn't download it. I looked at browser's console, but I couldn't find any error message. There was no message in browser's console.
Could you give me any advice? Thank you in advance.
This is my main.js
'use strict';
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
return firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
// Checks that the Firebase SDK has been correctly setup and configured.
function checkSetup() {
if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
window.alert('You have not configured and imported the Firebase SDK. ' +
'Make sure you go through the codelab setup instructions and make ' +
'sure you are running the codelab using `firebase serve`');
}
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
// Create a reference from a Google Cloud Storage URI
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
This is index.js (Cloud Functions)
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
const textToSpeech = require('#google-cloud/text-to-speech');
exports.myFunction = functions.firestore
.document('messages/{id}')
.onCreate((change, context) => {
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
// The text to synthesize
const text = 'Hello world';
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
var bucket = admin.storage().bucket('adva********.appspot.com');
var file = bucket.file('audio/sub.mp3')
// Create the file metadata
var metadata = {
contentType: 'audio/mpeg'
};
// Performs the text-to-speech request
const [response] = await client.synthesizeSpeech(request);
return await file.save(response.audioContent, metadata)
.then(() => {
console.log("File written to Firebase Storage.")
return;
})
.catch((error) => {
console.error(error);
});
}
quickStart();
});
This is index.html
<!--./advance/index.html-->
<!doctype html>
<html lang="ja">
<head>
<meta name="robots" content="noindex">
<title>音読アプリ アドバンス</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c&display=swap" rel="stylesheet">
<style>
#text {width: 100%; height: 300px; font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 22px;}
#download {font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 28px;}
</style>
</head>
<body>
<textarea id="text" class="form-control" name="text" placeholder="ここに英文を入力してください。" maxlength="3000" minlength="1"></textarea>
<br>
<div style="text-align:center">
<input id="download" class="btn btn-primary" type="submit" value="音声をダウンロード">
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/7.14.3/firebase-app.js"></script>
<script src="/__/firebase/7.14.3/firebase-auth.js"></script>
<script src="/__/firebase/7.14.3/firebase-storage.js"></script>
<script src="/__/firebase/7.14.3/firebase-messaging.js"></script>
<script src="/__/firebase/7.14.3/firebase-firestore.js"></script>
<script src="/__/firebase/7.14.3/firebase-performance.js"></script>
<script src="/__/firebase/7.14.3/firebase-functions.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
browser's developer tool's Network tab
The problem is that you are likely trying to download before the file is created by your cloud function, since you are running the cloud function as a event trigger that automatically runs every time a document is created, but at the same time you are trying to download that file on your front end. This lack of syncronism creates this odd behaviour you are seeing.
In order to fix that there are a couple of things you should do:
Convert your cloud function to a http triggered function instead of a event triggered function.
This will make it so your function can be invoked by your front end after the creation of the document and before you are trying to download it, it could look like this:
exports.myFunction = (req, res) => {
//you can get the id of the document sent on the request here
const id=req.body;
...
};
Also, you might want to check this documentation for more details on this type of trigger
Create a download function and add all your code for the download to it and add synchronicity to your operations on your front-end.
With this your code will execute in the proper order, and you main.js will look like this:
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(docRef){
var obj = {
method: 'POST',
body: docRef.id
};
//calls function that adds to storage
fetch("YOUR_FUNTION_URL_HERE", obj).then({
//actually downloads
download();
}).catch(error) {
console.error('Failed to call cloud function', error);
});
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
function download(){
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
NOTE: This is all untested but it will be a good starting point for your to start the changes necessary to your code.
I hope someone may still find this useful. A hack around is to create an express server/lambda/cloud function to download file and send it back to the browser via the download method. Check bellow code
const express = require("express");
const app = express();
var fs = require("fs");
const request = require("request");
app.get("/", (req, res) => {
const { filename, fileUrl } = req.body;
const file = fs.createWriteStream("filename");
request.get(fileUrl).on("response", function (response) {
var pipe = response.pipe(file);
pipe.on("finish", function () {
res.download(filename, function (err) {
if (err) {
console.log(err); // Check error if you want
}
fs.unlink(yourFilePath, function () {
console.log("File was deleted"); // Callback
});
});
});
});
});
app.listen(3000, () => console.log("Server ready"));

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.

Websockets over WSS:// doesn't appear to fire events on server

I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.

Failed to load resource - Socket.IO

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

Categories

Resources