I am trying to use sockets in my api. However I could not see the logs in the console.
The only output I see is:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000
Here is my server.js file:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const db = require('./config/db');
app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err);
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('client connected');
socket.on('disconnect', function () {
console.log('disconnect');
});
});
})
and the index.html is:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>Hello world</body>
</html>
I see Hello world on the web browser, but I could not see 'client connected' on the console log.
Update: In your browser client you can see error in console.log http://localhost:8000/socket.io/socket.io.js 404 and (index):6 Uncaught ReferenceError: io is not defined
You have attach socket handler to a http server var io = require('socket.io')(server);, but in your code you start web server by express server
app.listen(port,() => {
console.log("We are live on"+port);
});
change it to
server.listen(port,() => {
console.log("We are live on"+port);
});
I have created a new .js file and listening to port 3000 instead of 8000 worked for socket.io
appsocket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket){
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now I am able to see the logs on console when I call localhost:3000 instead of localhost:8000
Related
So I am coding this web on Heroku and I try to integrate a socket into the setup. But the problem is that I cannot make both my Heroku app and socket.io server listen to the same port.
The default port for Heroku seems to be 5000 and for socket.io seems to be 3000.
If I try to change either of the ports to the same as the other, then the EADDRINUSE error pops up.
However, if I don't, then the two processes seems to operate separately
when I run npm start, then the terminal says
Listening on 5000
listening on xoxo 3000
And when I turned on to localhost:3000 it actually works ( the socket.io ), but on localhost:5000 it obviously doesn't. As a matter of fact, it also doesn't work on the Website that Heroku generated for me (only the localhost:5000 showed up)
The code lines below are from my index.js file.
How could I fix this? Thank you in advance.
const express = require('express');
const app = express();
const path = require('path')
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const PORT = process.env.PORT || 5000;
const INDEX = '/index.ejs'
app.listen(PORT, () => console.log(`Listening on ${ PORT }`))
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));
io.on('connection', (socket) => {
socket.on('playerEvent', (msg) => {
console.log(msg);
});
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.broadcast.emit('hi');
});
server.listen(3000, () => {
console.log('listening on xoxo 3000');
});
//socket.on('playerEvent', function(msg){
// console.log(msg);
//});
So basically what i am trying to do is build a chat app with a login system but for some reason i cant put it together and i am getting an error when i join to the room the chat.hbs can't find the socket.io.js file and also the main.js is getting a reference error with the const socket = io(); (the chat app works fine without the login system)
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not definedat main.js:11
This is the app.js file
const express = require("express");
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = "Bot";
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(cookieParser());
app.set('view engine', 'hbs');
//eldönti az útvonalat
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
This is the main.js
const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');
// Felhasználó név és szoba név URL-ből
const { username, room } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const socket = io();
// Csatlakozik chat szobába
socket.emit('joinRoom', { username, room });
// Lekérdezi a szobát felhasználókat
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
And the chat.hbs
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
Well the problem was that I used:
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
instead of:
server.listen(5001, () => {
console.log("Server started on Port 5001");
})
Szia, you will need to wait for the DOM to load.
window.addEventListener('load', function () {
// Your code goes here
const socket = io();
socket.on("connect", () => {
// you can only emit once the connection is established.
socket.emit('joinRoom', { username, room });
});
})
Hey so i just started to learn node js today and i am using express with ejs and trying to add a socket io server / chat but i can't seem to work out why i can't get it to work.
The page loads but does not connect to the socket server.
server.js:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
// EJS
app.use(expressLayouts);
app.use(express.static("public"));
app.set('view engine', 'ejs');
// Routes
app.use('/', require('./routes/index.js'));
app.use('/chat', require('./routes/chat.js'));
app.use((req, res, next) => res.redirect('/'));
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port)
});
routers/chat.js
const express = require('express');
const router = express.Router();
const server = require('http').createServer();
const io = require('socket.io')(server);
// Chat Page
router.get('/chat', (req, res) => {
res.render("chat/chat");
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
});
});
module.exports = router;
views/chat/chat.ejs:
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
Error:
Uncaught ReferenceError: io is not defined
You cannot source /socket-lib/socket.io.js,
you must source http://yourwebsite.com:12345/socket.io/socket.io.js.
bascily, you'll need to provide full source for the server adress.
The server automatically does the rest for you.
Source: https://stackoverflow.com/a/12160485/3010171
also. you might try out ./socket-lib/socket.io.js with a . before the slash
I am trying to connect my front-end which is on a online text editor to my Node server. I am hitting network error strict-origin-when-cross-origin and it is not hitting the Socket IO listener. Please let me know what is causing this error & how to fix it. Thanks!
Here is the Node.js code:
const cors = require('cors');
const app = express();
app.options('*', cors())
app.all('*', function(req, res) {
res.send("Oops, incorrect URL")
});
const server = http.createServer(app).listen(process.env.PORT, () => {
console.log('Express server listening on port 1337');
});
var io = require('socket.io')(server);
io.set('origins', '*:*');
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
console.log("CONNECTED!")
});
Here is the front-end:
import io from 'socket.io-client'
var socket = io('https://myserver.com/', {secure: true});
socket.emit('chat message', "testing");
I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});