I'm trying to add instant messaging to an existing app. But I'm not sure how should configure socket.io module.
I've already tried the following:
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const config = require('./config/config.js');
var expressConfig = require('./config/express.js').front,
models = require('./app/models'),
passConfig = require('./config/passport-front.js');
const app = expressConfig();
const passport = passConfig();
app.set('port', config.frontPort);
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('Connected');
});
models.sequelize.sync().then(function () {
var server = http.listen(app.get('port'), function () {
console.log('Express server listening on port ' + server.address().port);
});
});
module.exports = http;
Since connected is not being logged when I open a page I'm assuming something is missing. Where is my mistake?
You didn't show your client-side code so it's hard to tell you what's wrong. Do you get any error in the browser? What is the network traffic on the browser? Without that it's hard to tell anything specific.
Take a look at this answer:
Getting data from/writing data to localhost with Express and Socket.io
It has a working example of something similar to what you're trying to do.
In general - remember that you need to include the socket.io client-side code in the browser:
<script src="/socket.io/socket.io.js"></script>
and then you need to connect with io() with something like:
var s = io();
s.on('color', function (color) {
document.body.style.backgroundColor = color;
});
The 'color' here is just an example that comes from this project on GitHub:
https://github.com/rsp/node-live-color
It's an example of a website that changes colors selected in messages that come vie socket.io.
Related
I am using Socket.io in my NodeJS backend. However, the sockets do not work. For example, one should receive a link and then send them to all other rooms under the same code, but the code is not executing. In my heroku logs I receive no errors but when I inspect element the page I get
polling-xhr.js:268 GET https://localhost:5000/socket.io/?EIO=3&transport=polling&t=NDADDNH net::ERR_CONNECTION_REFUSED
and
Failed to load resource: net::ERR_CONNECTION_REFUSED
I have looked into similar problems from this forum and made several changes but none of them have solved the issue. Also a bunch of the posts answer with solutions for ws in general which I don't understand at all :/
From what I read the issue might be with my ports? I followed a few of them but the same errors still occured.
Socket.io:
/***BACKEND***/
const express = require('express');
const path = require('path');
const app = express();
let rooms = [];
/***SERVER***/
const port = process.env.PORT || 5000;
server = app.listen(port, function(){
console.log('App is listening on port ' + port)
});
/***SOCKET.IO***/
const socket = require('socket.io');
io = socket(server);
io.on('connection', (socket) => {
//bunch of functionality
}
and then in my client I am using
this.socket = io('localhost:5000');
//one of the functions
this.syncQueue = () => {
this.socket.emit('SYNC_QUEUE', {
activeRoom: this.props.getRoom()
});
}
this.socket.on('RECEIVE_QUEUE', newQueue => {
props.onAddToQueue(newQueue);
});
FYI Everything works on localhost
Localhost will not work on the server and if you are using default namespace you no need to specify the URL. So try this, this.socket = io()
On the client side, you're trying to connect to localhost:5000 instead of the URL Heroku provides. Try this this.socket = io('heroku url goes here').
While working with localhost I used the following code to implement socket functionality-
Server Side
var express = require('express');
var app = express();
const io = require('socket.io')(5000);
Client Side
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>const socket = io.connect('http://localhost:5000');</script>
The above code worked fine for me locally. Earlier tried use the code given in the official documentation, but it did not work. I got a 404 error when trying to load socket.io.js file and it said 'io is not defined' on the client side. That code is given below-
Server Side
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
Client Side
<script src="/socket.io/socket.io.js"></script>
<script>var socket = io.connect('http://localhost');</script>
Now I need to deploy the app to Heroku and don't know how to do the socket functionality. I tried both the above ways but none worked in Heroku. I am getting '404 error' and 'io is not defined'. The server-side code is written in ./app.js and client-side code written in ./public/index.html.
How do I get this socket functionality to work in Heroku and also why is the official code not even working locally?
Trying to get the same thing working, don't have all the answers but on heroku you need to grab the port from the environment variable.
// Needed for Heroku serving
if (process.env.PORT > 0)
port = process.env.PORT;
else
port = 5000;
// create the express server (app) and the socket io server (io)
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
Client Side
const socket = socketIOClient('APPNAME.herokuapp.com:80');
socket.emit("MsgType", "Payload")
I'm pretty new to NodeJS and trying to get Socket.IO running with an Express application. I've tried to stick to the docs and tutorials as close as possible, but in the end, socket.io.js cannot be found on client side.
The server is being started as follows:
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() { debug('...') } );
Routing/serving pages:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
Including socket.io:
var express = require('express');
var http = require('http').Server(express);
var io = require('socket.io')(http);
And in the HTML file, for clients:
<script src="/socket.io/socket.io.js" type="text/javascript">
But when loading the page, this JS-file is never found. I suspect that including socket.io via that previously created http server is somehow wrong... Or am I missing something else?
Update
I just found out that the snipped that includes socket.io is executed before the server is started (first snippet). They're in different files and the server-start one (named www.js) is configured as "start" script in package.json, the other one (websockets.js) required indirectly by that.
If I put
var io = require('socket.io')(server);
at the end of www.js, everything works just fine. But is there a way to do it from websockets.js, which is loaded before, e.g. by a server start callback function?
Try specifying the full path, like this
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
And connect to your server from client side:
var socket = io.connect('http://localhost:8000/');
also check if socket.io module is available in your node_modules directory.
I'm actually working on a little project, where i'm supposed to recreate a drawing multiplayer game with node.js, mongoDB, socket.io and canvas.
The drawer is working like a charm, and the server seems to work well too. I got my register/login/sessions and database up and working, the only problem is socket.io. When an user is joining the game room, he can see the drawer and tools, but no connection. Why ? The browser can't find socket.io.js.
What I did :
I verified if it was installed, it is with npm install socket.io.
I checked if the server was starting it when turning the server on : Got "socket.io started" in my console.
I checked my HTML code, here it is :
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
According to the billions of tutorials/dev sites/help subjects, this is supposed to work. But it's not. When opening the console of my browser, I got this :
X GET http://localhost:1337/socket.io/socket.io.js NOT FOUND.
I don't know where is the problem, I can't figure this out and it's giving me a huge headache.. So I'm here.
Thanks in advance for helping ! :)
Given the code in your comment, you're not using the correct variable for initializing socket.io.
Try this:
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
...
So instead of having socket.io 'listen' on the Express app instance, it should listen to what app.listen(...) returns (which happens to be an http.Server instance).
For anyone landing here because they're going through the v4.x socket.io get started example, all you need to do is add another endpoint to your index.js file
index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// add this
app.get('/socket.io/socket.io.js', (req, res) => {
res.sendFile(__dirname + '/node_modules/socket.io/client-dist/socket.io.js');
});
///
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
I have changed my files to look as shown below. The javascript console shows nothing and the web page shows nothing. Just a blank screen. Does anybody know of a web site which uses socket.io. I would like to inspect the code to see how they do it since none of the examples on the socket.io page work for me. Does anybody know if extra ports need to be allowed in the iptables file?
Using the Chrome browser, if I goto the javascript console and goto the Network tab I get successes but the last call says Pending ??? It looks like it is hung. Could this be a firewall issue?
/socket.io/1/websocket
GET
101
Switching Protocols
Pending
Other
127 B
0 B
Pending
it is Pending in selector.js on line 168:
document.body.appendChild(menuDiv);
Maybe this is why I am not seeing anything? It is properly serving up socket.io/socket.io.js
Files below:
//app.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
var port = 80;
var io = require('socket.io').listen(server, {
log : false
});
io.sockets.on('connection', function(socket) {
socket.on('hi', function(data) {
console.log('yay');
socket.emit('hello');
});
});
server.listen(port);
public/index.html
//index.html
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi');
});
chat.on('hello',function(){
console.log('yay got hello');
});
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});
</script>
You're using namespaces news and chat even though your server doesn't implement them correctly.
You javascript connection should look like this instead:
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});