GET http://js:port/socket.io/1/ 404 not found - javascript

Socket.io is having issues connecting up.
This is my Server code:
function chatserver(){
var express = require('express'),
app = express(),
server = require('http').createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port '+ app.get('port'));
});
var io = require('socket.io').listen(server),
users = {};
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (data in users){
callback(false);
} else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback){
var msg = data.trim();
console.log('after trimming message is: ' + msg);
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
if(ind !== -1){
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if(name in users){
users[name].emit('whisper', {msg: msg, nick: socket.nickname});
console.log('message sent is: ' + msg);
console.log('Whisper!');
} else{
callback('Error! Enter a valid user.');
}
} else{
callback('Error! Please enter a message for your whisper.');
}
} else{
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
}
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});
}
My HTML script code:
jQuery(function($){
var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');
var $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $nickBox.val(), function(data){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else{
$nickError.html('That username is already taken! Try again.');
}
});
$nickBox.val('');
});
socket.on('usernames', function(data){
var html = '';
for(i=0; i < data.length; i++){
html += data[i] + '<br/>'
}
$users.html(html);
});
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val(), function(data){
$chat.append('<span class="error">' + data + "</span><br/>");
});
$messageBox.val('');
});
socket.on('new message', function(data){
$chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
});
When I load up the website at first it's OK. But as soon as I click the chat box, in inspect elements/console I get to see "GET http://'js':5001/socket.io/1/?.." error appear. Please advise.

In server code, change this:
server = require('http').createServer(app).listen(port),
io = require('socket.io').listen(server),
to
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server);
If you are in http server not express.io server, use this:
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});

Your main problem is client Jquery script.
var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');
It is not the proper way to server socket.io.js to client.
You need to change it to http://<ip/domain>:<port>/socket.io/socket.io.js
If Socket.io Server listens properly to your HTTP server, it will automatically serve the client file to via http://<ip/domain>:<port>/socket.io/socket.io.js. You don't need to find it or copy in public accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)

Related

How to have two different chats in two different pages of the same website using Socket.io

I'm not really expert yet, anyway thank you for helping me. I created a website with two different pages. Now I want to get two different chats, one for the first page and one for the second. I need to use socket.io. I've actually already implemented the code to get one working chat, but when I type something on this chat, the message appears even in the other. So this means that the two chats are linked each other. That is the problem because I want them to be indipendent. Id est I want them to work with their own pages which have got the send button, the input field for the message and the input field for your name. So the two pages can work alone, but i don't know how.
My code is divided into 2 pages: index.js and chat.js. Here there is Index.js:
var express = require('express');
var socket = require('socket.io');
//app setup
var app = express();
var server = app.listen(8080, function(){
console.log('ascoltando la richiesta alla porta 8080');
});
//static
app.use(express.static('public'));
//socket setup
var io = socket(server);
io.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
And here there is the code placed in chat.js (which is the file linked in one html page, the other page is not currently linked with anything):
//connessione
var socket = io.connect('http://localhost:8080'); // è una variabile socket diversa da quella in index.js
//query
var message= document.getElementById('message');
var handle = document.getElementById('handle');
var button = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
//scrollbar sempre in basso
function updateScroll(){
var element = document.getElementById("output");
element.scrollTop = element.scrollHeight;
}
//emit eventi
button.addEventListener('click',function() {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
//listen eventi
socket.on('chat', function(data){
if (data.message !== "" & data.handle !== "") {
if (handle.value === data.handle) {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=inviato>' +'<span id="utente">'+'Tu' +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
} else {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=ricevuto>' +'<span id="utente">'+data.handle +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
}
}
});
socket.on('typing', function(data) {
feedback.innerHTML = '<p>'+ data + ' sta scrivendo...' + io.engine.clientsCount;
});
Thank you so much
thank you but I've probably not understood because it doesn't work anymore: when i press the send button, nothing happens.
here there are the two codes updated.
index.js:
var express = require('express');
var io = require('socket.io')(server);
//app setup
var app = express();
var server = app.listen(8080, function(){
console.log('ascoltando la richiesta alla porta 8080');
});
//static
app.use(express.static('public'));
//socket setup
var room1 = io.of('/room1');
var room2 = io.of('/room2');
room1.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
room2.on('connection', function(socket){
console.log('fatta la connessione socket', socket.id);
socket.on('chat', function(data) {
io.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
chat.js:
//connessione
var socket = io.connect('http://localhost:8080/room1');// è una variabile socket diversa da quella in index.js
//query
var message= document.getElementById('message');
var handle = document.getElementById('handle');
var button = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
//scrollbar sempre in basso
function updateScroll(){
var element = document.getElementById("output");
element.scrollTop = element.scrollHeight;
}
//emit eventi
button.addEventListener('click',function() {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
//listen eventi
socket.on('chat', function(data){
if (data.message !== "" & data.handle !== "") {
if (handle.value === data.handle) {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=inviato>' +'<span id="utente">'+'Tu' +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
} else {
feedback.innerHTML= "" ;
output.innerHTML +='<p id=ricevuto>' +'<span id="utente">'+data.handle +'</span> <br> ' + data.message +'</p> <br>';
updateScroll();
document.getElementById('message').value='';
}
}
});
socket.on('typing', function(data) {
feedback.innerHTML = '<p>'+ data + ' sta scrivendo...' + io.engine.clientsCount;
});

MIME type ('text/html') Error

So I am trying to add require.js to my project that I am using jQuery and Socket.io to create but I keep getting this error.
I was wondering what is going on here? I am adding my code like this
<script src="js/require.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function ($) {
var socket = io.connect();
var $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function (e) {
e.preventDefault();
socket.emit('new user', $nickBox.val(), function (data) {
if (data) {
$('#nickWrap').hide();
$('#contentWrap').show();
} else {
$nickError.html('Name is taken! Choose a New one!');
}
});
$nickBox.val('');
});
socket.on('usernames', function (data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += data[i] + '<br/>'
}
$users.html(html);
});
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val(), function (data) {
$chat.append('<span class = "error"' + data + "</span><br/>");
});
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append('<span class= "msg"<b>' + data.nick + ': </b>' + data.msg + "<span/><br/>");
});
socket.on('whisper', function (data) {
$chat.append('<span class = "whisper"<b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
});
</script>
Edit
Here is my server code
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
users ={};
server.listen(3000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
res.sendFile(__filename + 'js/bower_components/crypto-js/crypto-js.js');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if(data in users) {
callback(false);
} else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket
updateNames();
}
});
function updateNames(){
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback){
var msg = data.trim();
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
if(ind !== -1){
var name = msg.substr(0, ind);
var msg = msg.substr(ind + 1);
if(name in users){
users[name].emit('whisper', {msg: msg, nick: socket.nickname});
console.log('hi');
} else{
callback('Error! Enter a valid user!');
}
}else{
callback("Error! Enter a pm");
}
} else {
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
}
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNames();
});
});
This error basically means that js/require.js does not contain valid JS code.
Double check that its not including any extraneous code or characters.

Send massage based on some interval in Node JS Websocket

I'm new to Node JS. I wrote NodeJs code it is working fine. But is sending when send a message from a client but I want to send message repeated manner.
Send response when client send any message:
var webSocketServer = require('ws').Server;
var http = require('http');
var fs = require('fs');
var webSocketServerObject = new webSocketServer({ port: 9060 });
webSocketServerObject.on('connection', function (socketObject) {
socketObject.on('message', function (message) {
console.log('The' + message + 'Message Received from \n from IP ' + socketObject.upgradeReq.connection.remoteAddress);
socketObject.send("Received " + message);
});
socketObject.on('close', function (c, d) {
console.log('Disconnect ' + c + ' -- ' + d);
});
});
Above code is working fine(reference ) same code I modified based on interval but it not working.
Below modification:
webSocketServerObject.on('connection', function (socketObject) {
setInterval(function(){
socketObject.send("Hello...");
}, 10000);
socketObject.on('close', function (c, d) {
console.log('Disconnect ' + c + ' -- ' + d);
});
});
How I can make it in sever to keep sending messages.

Node.js Forever List shows application is running when it is not

I have a simple queue display application in node.js. It shows users in a queue on a display. The application runs fine. We have it running on many servers currently. The problem is that, on a few servers, after a while (forever list shows one example as running for 15 days) it stops responding and netstat shows nothing listening on port 3000.
Code:
// Module dependindex.html
var express = require('express'),
mysql = require('mys');
// Application initialization
var connection = mysql.createConnection({
host : 'mysql.host',
user : 'root',
password : 'pw',
database : 'db',
});
var app = express();
app.use(express.urlencoded());
app.use(express.static(__dirname + '/components'));
// Page configuration (html pages are tempulates)
app.get('/', function(req,res) {
res.sendfile(__dirname + '/index.html');
});
// Application routes
// mysql calls/logic here
app.post('/', function(req, res){
var query = "SELECT aa.id, aa.first_name, aa.last_name, aa.gwf, ac.counter_stage, aa.queue_call_by_flag, ac.counter_name FROM `agent_counters` ac LEFT JOIN `applicants` aa ON aa.id = ac.next_applicant WHERE ac.call_next = 1 AND ac.next_applicant is not null";
connection.query(query, req.body, function(err, rows, fields) {
if (err) throw err;
var obj = {};
var prop = "";
var gwf_name = ""
for (var i = 0; i < rows.length; i++) {
var current_stage = "";
switch (rows[i].counter_stage) {
case "documentation":
current_stage = "Documentation";
break;
case "biometrics":
current_stage = "Biometrics";
break;
case "interview":
current_stage = "Interview";
break;
}
prop = "gwf" + i;
if (rows[i].queue_call_by_flag == 'gwf') {
gwf_name = rows[i].gwf;
} else {
gwf_name = rows[i].first_name + ' ' + rows[i].last_name;
}
obj[prop] = gwf_name + '|' + rows[i].counter_name + '|' + current_stage + '|' + rows[i].id;
}
res.send(JSON.stringify(obj));
});
});
// Begin listening
app.listen(3000);
console.log("Express server listening on port %d in %s mode", '3000', app.settings.env);
I have set the server to run with the Forever module Forever with the command:
Forever start app.js
Any help would be appreciated.

simple connection error socket.io

I have a simple tcp connection server in nodejs + socket.io can send data to the server but I have no comeback.
excuse my english I'm from Brazil
see the code.
client code:
if(newY !== ymouse || newX !== xmouse)
{
socket.emit('chat', {playerX: playerX, playerY: playerY});
}
socket.on('chat',
function (data)
{
console.log(data)
// $("p#data_recieved").append("<br />\r\n [position] {" + data.msgr + ": playerX = " + data.playerX + ", playerY = " + data.playerY + "}");
document.getElementById("vy").innerHTML = data.X;
document.getElementById("vx").innerHTML = data.y;
}
server code:
var io = require('socket.io').listen(8000);
io.sockets.on('connection',
function (socket)
{
socket.on('chat',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
console.log('Chat message by ', name);
console.log('error ', err);
console.log('X: ' + data.playerX);
console.log('Y: ' + data.playerY);
sender = name;
});
socket.broadcast.emit('chat', { playerX : data.playerX, playerY : data.playerY, msg : data, msgr : sender});
});
socket.on('position',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
sender = name;
});
if(sender == 'unregistered')
return;
var playerX = data.playerX;
var playerY = data.playerY;
socket.broadcast.emit('position', {msgr : sender, playerX : playerX, playerY : data.playerY});
});
socket.on('register',
function (name)
{
socket.set('nickname', name,
function ()
{
io.sockets.emit('chat', {msg : "naay nag apil2! si " + name + '!', msgr : "mr. server"});
});
});
});
how can you see I can
  send data to the server but
  no response
server seems to work well
I leave an example of a simple connection in which you can inspire
Server:
var simple = io
.sockets
.on('connection', function(socket) {
socket.on('message', function(data) {
socket.broadcast.send(data);
});
socket.on('disconnect', function() {
// handle disconnect
});
});
Client:
var socket = io.connect();
var content = $('#simple-content');
socket.on('connect', function() {
$('#simple-form').css('display', 'block');
content.append($('<p>').text('Connected'));
});
socket.on('message', function(msg) {
content.append($('<p>').text(msg)
.append($('<em>').text(' from server')));
});
$('#simple-form').submit(function(e) {
e.preventDefault();
var textObj = $('#simple-text');
var msg = textObj.val();
textObj.val('');
content.append($('<p>').text(msg)
.append($('<em>').text(' from me')));
socket.send(msg);
});
I hope it will be helpful!

Categories

Resources