Express js chat application:404 error on socket.io.js file - javascript

I am trying to develop a chat application using Express js(jade template ) and socket.io.Here is my app.js
var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io')(http);
var app = express();
//start chat with socket io
io.sockets.on('connection',function(socket){
console.log("connection");
socket.on('send message',function(data,callback){
var msg=data.trim();
if(msg==null){
callback("enter a messsage");
}else{
console.log("chat message"+msg);
io.sockets.emit('new message',{msg:msg});
}
});
});
//end socket
Here is my chat.js file on client side
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
var $message=$('#message');
var $messageForm=$('#send-message');
//opens a connection and send to sever
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$message.val(),function(data){
console.log("data"+data);
});
$message.val('');
});
//read the chat messages from users
socket.on('new message',function(data){
console.log('data.msg');
});
});
chat.jade file
<form id="send-message">
<input type="text" id="message">
<input type="submit" value="submit"/>
</form>
<script src="http://localhost/api/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
I will get 404 error on this file http://localhost:3000/socket.io/socket.io.js. Also get a Uncaught ReferenceError: io is not defined in chat.js script.I think this is because of missing socket.io.js file.

You have a couple of issues.
Serving static files in your jade templates you should be using something like this:
link(rel='text/javascript', href='/js/socket.io.js')
These files will normally be contained within a public directory in your express app.
Then in your app.js you should have something like:
app.use(express.static('public'));
Its explained here on the express site - http://expressjs.com/starter/static-files.html
Elsewhere
Uncaught ReferenceError: io is not defined
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
This is because you havent defined io on your client. You call connect on something called io but havent declared/defined io anywhere.
Also
You havent created a socket server on your app side. You should be doing something along the lines of:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
});
});
Example
Socket.io have an example chat app on github that you should use as reference.
Your chat.js would be the equivalent of their public/main.js
Your chat.jade is equivalent to their public/index.html
and your app.js matches their index.js

Related

POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQUneY3 400 (Bad Request) in ejs and nodejs

I am very new to this socket.io.
I have the code this is a node server code:
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var socketIO = require("socket.io")(http);
var socketID = "";
socketIO.on("connection", function (socket) {
console.log("User is conneected ", socket.id);
socketID = socket.id;
});
And here is the code for a ejs file:
......
<script src="/public/js/socket.io.js"></script>
<script>
......
var socketIO = io("http://localhost:3000");
......
</script>
......
And the socket.io.js file is here:
I tried but nothing is working. The same error pops whenever I refresh the page.
I am very new to this and I really want to get it sorted as soon as possible!!
I already have a listen function just after socket.on:
http.listen(3000, function () {
console.log("Server has started running!!");
.........................
.............
})
The below code is working for me.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log(socket);
})
server.listen(3000, function(){
console.log('listening on *:3000');
});
<script src="/socket.io/socket.io.js" > </script>
<script>
$(function () {
var socket = io.connect();
});
</script>
socket.io.js that you have mentioned is the same as that from the https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js... check the installed version of serail io in package.json and place the same version here in the path socket.io/2.2.0 it will work
Please Check versions of socket.io in your Frontend and Backend. It should be compatible. I had same issue so I solved it with version change. Like I had 2.2.0 in my frontend so I install 1.7.2 in backend or same as frontend.

HTML file can't find embedded js files

I'm currently trying to make a game using Node.js, Express, and Socket.io. However, when I attempt to run it locally I get a 404 error stating that my javascript files can't be found. My file structure looks like this:
root
| game
| | game.html
| | game.js
| index.js
And my code looks like this:
index.js
//Dependencies
var express = require('express'); //Pulls in Express framework
var http = require('http') //Pulls in http module
var socketio = require('socket.io'); //Pulls in Socket.io framework
//Instance Declarations
var app = express(); //Creates an Express instance
var server = http.createServer(app); //Creates an http server using the Express framework
var port_to_listen = process.env.PORT || 3000; //Specifies which port to listen on
var socket = socketio(http); //Creates Socket.io instance related to the server just created
//Default page displayed, always sent to index.html
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
//Tells the server to listen for any incoming inconnections
server.listen(port_to_listen, () => {
console.log(`listening on ${port_to_listen}`);
});
socket.on('connection', function(client) {
console.log('Connection made')
});
//Testing to ensure socketio works
setInterval(function() {
socket.sockets.emit('message', 'hi!');
}, 1000);
game.js
var socket = io();
socket.on('message', function(data) {
console.log(data);
});
game.html
<html>
<head>
<title>A Multiplayer Game</title>
<style>
canvas {
width: 800px;
height: 600px;
border: 5px solid black;
}
</style>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script type = "text/javascript" src="game.js"></script>
</html>
The error messages look like this:
What should I do to fix these errors?
Edit:
These errors also still persist when I change the src path for game.js to
<script type = "text/javascript" src="/game/game.js"></script>
You have only one route that serves files:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
The rest of the files (your css, js, etc.) are not served automatically
You need to create route(s) for that, like explained here Serving static files in Express

Node.js connection with socket.io not working

Hey guys that's one of my first time using node.js and socket.io so i will try to be clear as possible. So i am doing a tutorial for a chat.
And i don't know why the connection is not working when i am running my html page :
http://localhost:8000/user/tchat (Symfony project)
I don't have the
console.log('New user'); (i run the server with "node server.js")
But when i am going to :
http://localhost:1337/
i have the
console.log('This is a test');
I have 2 js files and one html page :
Server.js :
var http = require('http');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function(socket) {
console.log('New user');
});
Client.js :
(function($){
var socket = io.connect('http://localhost:1337');
})(jquery);
And the scripts of the html page :
<script src="http://localhost:1337/socket.io/socket.io.js"></script>
<script src="../js/js/client.js"></script>

Node.js + ExpressJS + Socket.IO TypeError: obj.on is not a function

I have unfortunately hit a roadblock in my work. I have a node.js+ExpressJS back end hooked up to a front end via Socket.io and have created the server and client as follows:
app.js:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// Routes and io.on statement with listeners on 'connection'
server.listen(2000);
io.listen(2000);
Index.html:
<!doctype html>
<!--- html stuff --->
<script src='/socket.io/socket.io.js'></script>
<script src='/js/jquery.min.js></script>
<script>
$(document).ready(function() {
var socket = new io.Socket('localhost', {port: 2000});
socket.connect();
// other js that doesn't get picked up
});
</script>
What happens when I crack open my console in browser is:
io.connect();
TypeError: obj.on is not a function
Did I miss something, or is a stroke of misfortune fall into my code?
Please try changing in your index.html:
var socket = new io.Socket('localhost', {port: 2000});
socket.connect();
to:
var socket = io.connect();

Redis Pub/Sub not displaying published message in client using redis-cli

Hello guys i'm having a problem in redis pub/sub because my client does not show the message i've published in redis-cli. I used the codes found here in stackoverflow and i made some modification. Here is the link and code. I hope you can help me, my goal is to publish the message to the client index.html using redis publish in redis-cli. I've done this before but i can't make it work again. Thanks in advance guys.
Here is my client index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- <script src="/javascripts/socket.js"></script> -->
</head>
<body>
<div id="content"></div>
<script>
var socket = io.connect('http://localhost:3000');
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function (message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
Here is my server.js
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http');
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
var publish = redis.createClient();
app.listen(3000);
console.log("Express server listening on port 3000")
app.get('/', function (req,res) {
res.sendfile(__dirname + '/public/index.html');
});
socket.on('connection', function (client) {
var subscribe = redis.createClient();
subscribe.subscribe('pubsub');
subscribe.on("message", function (channel, message) {
publish.send(message);
});
publish.on('message', function (msg) {
});
publish.on('disconnect', function() {
subscribe.quit();
});
});
Redis will not send data to connected clients for you. You must instruct Socket.IO to emit data:
subscribe.on("message", function (channel, message) {
socket.emit('message', message);
});

Categories