I have a problem connecting to my front end server socket on my back end
in my front end ( react ) i have this:
import React, { Component } from 'react';
import {Form,FormGroup, Label, Input, Button, Alert} from 'reactstrap';
import Header from '../../components/header';
import io from 'socket.io-client';
export default class Login extends Component {
constructor(props) {
super(props)
console.log(this.props);
this.state = {
message: this.props.location.state?this.props.location.state.message: '',
};
}
signIn = () => {
let socket = null;
async function connect () {
socket = io.connect('http://localhost:8080/');
}
connect();
}
render(){
return(
<div className="col-md-6">
<Header title="ReactJS Login"/>
<hr className="my-3"/>
<Button color="primary" onClick={this.signIn}> Entrar </Button>
</div>
);
}
}
in my back end:
const usersRouter = require('./routes/userRoutes');
const postRouter = require('./routes/post');
const matchRouter = require('./routes/matchRoutes');
const app = express();
const router = express.Router();
const socket = require('socket.io');
const server = app.listen(
port,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${port}`)
);
let io = require('socket.io')(server);
app.set("io", io);
io.on('connection', socket => {
require('./routes/socket')(socket);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});''
app.use(express.json());
app.use('/', router);
module.exports = app;
in my router folder i have this:
const socketController = require ('../controllers/SocketController');
module.exports = (socket) => {
socket.on('myevent', (message) => {
console.log('bateu aq');
socket.emit('myEvent', {message: 'hello world'});
});
};
I am also wondering how I could add a jwt validate middleware to my route that I have
I also don't know if this is the best code structure I can have to work with socket using routes and controllers, if anyone can help me how to improve it.
There is no code in your example that is actually interacting with the server. Please update the code as follows to determine the connections and events are working as per the question comments.
React:
async function connect () {
socket = io.connect('http://localhost:8080/');
socket.on('hello', (message) => {
console.log(message);
});
socket.on('myevent', message => {
console.log(message);
});
socket.emit('myevent', {foo: 'bar'});
}
Express:
module.exports = (socket) => {
socket.emit('hello', {data: 'this is a message'});
socket.on('myevent', (message) => {
console.log(message);
socket.emit('myevent', {message: 'OK'});
});
};
Related
I have my backend in NodeJS and frontend in NextJS. As soon I try to connect with the server for a WebSocket connection, the server connects the socket and immediately disconnects it.
This is what I get on my server as soon as I reload my frontend page:
user connected ---- OKGG9r0qvvBs0EWeAAAB test#test.com socket disconnected--- OKGG9r0qvvBs0EWeAAAB test#test.com
This is my server code:
import express from "express";
import dotenv from "dotenv";
import http from "http";
import { Server, Socket } from "socket.io";
import userRoutes from "./routes/users";
import { DefaultEventsMap } from "socket.io/dist/typed-events";
dotenv.config();
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: process.env.CLIENT_URL,
},
});
app.use(express.json());
app.get("/ping", (req, res) => res.status(200).send("Pong"));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "POST, GET");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
next();
});
interface SType extends Socket {
email?: string;
}
io.use((socket: SType, next) => {
const userEmail = socket.handshake.auth.email;
if (!userEmail) {
return next(new Error("Invalid email"));
}
console.log("userEmail-----", userEmail);
socket.email = userEmail;
next();
});
io.on("connection", (socket) => {
const users = [];
for (let [id, socket] of io.of("/").sockets) {
users.push({
userID: id,
email: (socket as any).email,
});
socket.emit("users", users);
}
socket.broadcast.emit("user connected", {
userID: socket.id,
email: (socket as any).email,
});
console.log("user connected ---- ", socket.id, (socket as any).email);
socket.on("disconnect", () => {
console.log("socket disconnected---", socket.id, (socket as any).email);
(socket as any).email = "";
});
});
app.use("/users", userRoutes);
server.listen(PORT, () => console.log(`server running on port ${PORT}`));
this is code on client side
useEffect(() => {
if (userState) {
socket.auth = { email: userState.email };
}
}, [userState]);
useEffect(() => {
socket.on("users", (users: any) => {
console.log("users", users);
setUsers(users);
});
socket.on("user connected", (user: any) => {
setUsers((previousState: any) => [...previousState, user]);
});
}, [socket]);
I tried the solutions from stack overflow as well as socket.io documentation, but nothing seems to work. Does anyone know what is happening here?
I am creating a node.js app with a react client and an express/socketio backend and passport authentication. I'm trying to emit a socketio event from the client and then have the backend respond but it seems that the request is getting lost somewhere between when it's emitted to when the backend processes it.
Below are all the files I thought relevant to the problem at hand.
Backend is on localhost:5000 and client is on localhost:3000
As I said, everything goes well until the line marked in Organization.js. But at/after that line, the event is presumably sent but none of the corresponding routes in socket.js are hit.
Backend start file - app.js
'use strict';
import express from 'express'
import { createServer } from 'http'
import path from 'path'
import { fileURLToPath } from 'url';
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import index from './routes/index.js'
import session from 'express-session'
import passport from './src/auth.js'
import { Server } from 'socket.io'
import { CrashCollector } from 'crashcollector'
new CrashCollector('crash_logs', (err, exit) => {
console.log('Cleaning up...')
console.log('Saving some stuff...')
// Calls callback funtion executing process.exit()
// You can also just write process.exit() here
exit()
})
const app = express();
const server = createServer(app)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const io = new Server(server, {
cookie: { maxAge: 24 * 60 * 60 * 1000 },
cors: {
origin: 'http://localhost:3000',
credentials: true
}
})
const sessionMiddleware = session({
secret: "changeit", resave: false,
saveUninitialized: false
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(sessionMiddleware)
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
console.log('dev error handler')
res.status(err.status || 500);
res.end()
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
console.log('prod error handler')
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.set('port', process.env.PORT || 3000); //process.env.PORT = 5000
server.listen(app.get('port'), _ => {
console.log(`Server listening on port ${app.get('port')}`)
})
export {
io,
sessionMiddleware
}
Backend - socket.js
import { io, sessionMiddleware } from '../app.js'
import passport from '../src/auth.js'
import { getSequel } from '../src/database.js'
const wrap = middleware => (socket, next) =>
middleware(socket.request, {}, next);
io.use((_, next) => {
console.log('connection attempt')
next()
})
io.use(wrap(sessionMiddleware));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));
io.use((con, next) => {
console.log('socket check', !!con.request.user)
if (con.request.user) {
next()
} else {
next(new Error('unauthorized'))
}
});
io.on('connection', (con) => {
console.log(`new connection ${con.id}`);
con.on('confirm', cb => {
cb(con.request.user.name);
});
con.on('eventTable', _ => {
console.log('eventTable')
con.emit(con.request?.user?.getEvents()?.map(e => e.toJSON()))
})
});
Client start file - index.js
import React from 'react'
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App/App';
import { io } from 'socket.io-client'
import configs from '../package.json'
const container = document.getElementById('root');
const root = createRoot(container);
export const socket = io.connect(configs.proxy, { //configs.proxy = http://localhost:5000
withCredentials: true
})
socket.on('connect', _ => {
console.log('socket connect', socket.id)
})
socket.on('connect_error', _ => {
console.log('socket connect_error')
})
socket.on('disconnect', _ => {
console.log('socket disconnect')
})
socket.prependAny((eventName, ...args) => {
console.log(eventName, args)
})
root.render((
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
));
Client - App.js
import React from 'react'
import { Route, Routes } from 'react-router-dom'
import './App.css'
import Login from './pages/Login'
import Home from './pages/Home'
import LoginCheck from './helper/LoginCheck'
const App = () => {
console.log('app')
return (
<Routes>
<Route exact path="/" element={<LoginCheck />} >
<Route index element={<Home />} />
</Route>
<Route path="/login" element={<Login />} />
</Routes>
)
}
export default App;
Client - Home.js
import React, { useState } from 'react';
import Org from './Organization'
const Home = () => {
console.log('home')
return localStorage.getItem('isOrg') ? (
<Org />
) : (
'Employee'
)
}
export default Home;
Client - Organization.js
import React, { createElement, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'
import Countdown from 'ds-countdown'
import { socket } from '../../index'
const Org = () => {
console.log('org')
const setTable = (raffles) => {
console.log('cb eventTable')
JSON.parse(raffles).forEach(raffle => {
const row = createElement('tr')
const name = createElement('td')
name.append(raffle.name)
const num = createElement('td')
num.append(raffle.num)
const started = Date.parse(raffle.start) >= Date.now()
const countdown =
<><td>
<p style={{ color: started ? 'red' : 'green' }}>
{started ? 'Starts' : 'Ends'} in:
<div id={`timer${raffle.id}`} />
</p>
</td></>
const action = createElement('td')
const edit = createElement('button')
edit.addEventListener('click', e => {
//goto edit at raffle.id
alert('edit')
})
const end = createElement('button')
end.addEventListener('click', e => {
//set timer to 0
alert('start/end')
})
action.append(edit)
action.append(end)
row.append(name)
row.append(num)
row.append(countdown)
row.append(action)
document.getElementById('eventTable').append(row)
new Countdown({
id: `timer${raffle.id}`,
targetTime: started ?
raffle.end : raffle.start
})
})
}
useEffect(() => {
console.log('useEffect')
**socket.emit('eventTable')** //THIS IS WHERE IT BREAKS
socket.on('eventTable', setTable)
return () => {
socket.off('eventTable', setTable)
}
})
return (<>
<h1 style={{ textAlign: 'center' }}>
{localStorage.getItem('name')}
</h1>
<table style={{ marginLeft: 'auto', marginRight: 'auto' }}
border="1"><caption>
<h3>Scheduled Raffles</h3>
</caption>
<tbody id="eventTable">
<tr>
<th>Name</th>
<th>Num Participants</th>
<th>Countdown</th>
<th>Action</th>
</tr>
<tr>
<td>Test</td>
<td>10</td>
<td>10:10:04</td>
<td><button> Edit </button> <button> End Now </button> <button> Stop </button></td>
</tr>
</tbody>
</table>
</>);
}
export default Org;
I get no errors on the front end. In fact, the client says that a connection has been established, thanks to the socket.on('connect') in index.js. None of the console.logs in the socket.js file are getting activated, so I have reason to believe that the route isn't getting hit. I also activated Debugging on socket but the logs there don't help me very much:
Server listening on port 5000
socket.io:server incoming connection with id 1wpATq-xiQ1jHttwAAAA +2s
socket.io-parser decoded 0 as {"type":0,"nsp":"/"} +0ms
socket.io:client connecting to namespace / +0ms
socket.io:namespace adding socket to nsp / +0ms
socket.io:socket socket connected - writing packet +0ms
socket.io:socket join room f6lna-kbntjuwffpAAAB +3ms
socket.io-parser encoding packet {"type":0,"data":{"sid":"f6lna-kbntjuwffpAAAB"},"nsp":"/"} +7ms
socket.io-parser encoded {"type":0,"data":{"sid":"f6lna-kbntjuwffpAAAB"},"nsp":"/"} as 0{"sid":"f6lna-kbntjuwffpAAAB"} +1ms
POST /login 200 653.887 ms - 37
socket.io-parser decoded 2["eventTable"] as {"type":2,"nsp":"/","data":["eventTable"]} +3s
socket.io:socket got packet {"type":2,"nsp":"/","data":["eventTable"]} +3s
socket.io:socket emitting event ["eventTable"] +0ms
socket.io:socket dispatching an event ["eventTable"] +1ms
socket.io-parser decoded 2["eventTable"] as {"type":2,"nsp":"/","data":["eventTable"]} +15ms
socket.io:socket got packet {"type":2,"nsp":"/","data":["eventTable"]} +2ms
socket.io:socket emitting event ["eventTable"] +0ms
socket.io:socket dispatching an event ["eventTable"] +1ms
The server side socket.emit call should have an event name as the first argument.
con.emit('eventTable', con.request?.user?.getEvents()?.map(e => e.toJSON()))
The problem was I was starting the server before initializing the sockets.js routes. I had to do some reconfiguring on the backend, but basically the way I fixed it was making an express router in sockets.js, importing said router to app.js, then doing app.use('/socket', sockets), BEFORE calling server.listen(PORT). Below is the final state of my backend:
new Backend file - init.js:
import express from 'express'
import { createServer } from 'http'
import session from 'express-session'
import { Server } from 'socket.io'
import { CrashCollector } from 'crashcollector'
new CrashCollector('crash_logs', (err, exit) => {
console.log('Cleaning up...')
console.log('Saving some stuff...')
// Calls callback funtion executing process.exit()
// You can also just write process.exit() here
exit()
})
const app = express();
const server = createServer(app)
const io = new Server(server, {
cookie: { maxAge: 24 * 60 * 60 * 1000 },
cors: {
origin: 'http://localhost:3000',
credentials: true
}
})
const sessionMiddleware = session({
secret: "changeit", resave: false,
saveUninitialized: false
});
export {
server,
app,
io,
sessionMiddleware
}
app.js:
'use strict';
import express from 'express'
import path from 'path'
import { fileURLToPath } from 'url';
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import index from './routes/index.js'
import passport from './src/auth.js'
import { server, app, sessionMiddleware } from './init.js'
import sockets from './routes/sockets.js'
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(sessionMiddleware)
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', index);
*app.use('/sockets', sockets)* //This is the bit I was missing
// catch 404 and forward to error handler
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
console.log('dev error handler')
res.status(err.status || 500);
res.end()
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
console.log('prod error handler')
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), _ => {
console.log(`Server listening on port ${app.get('port')}`)
})
sockets.js:
import { io, sessionMiddleware } from '../init.js'
import passport from '../src/auth.js'
import { getSequel } from '../src/database.js'
import { Router } from 'express'
const router = Router()
const wrap = middleware => (socket, next) =>
middleware(socket.request, {}, next);
io.use((_, next) => {
console.log('connection attempt')
next()
})
io.use(wrap(sessionMiddleware));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));
io.use((con, next) => {
console.log('socket check', !!con.request.user)
if (con.request.user) {
next()
} else {
next(new Error('unauthorized'))
}
});
io.on('connection', (con) => {
console.log(`new connection ${con.id}`);
con.on('confirm', cb => {
cb(con.request.user.name);
});
con.on('eventTable', cb => {
con.request.user.getEvents()
.then(events => events.map(e => e.JSON()))
//I switched to a callback here, rather than emitting a new event
.then(mappedArray => cb(mappedArray))
})
});
export default router
Socket io.on is not working in NodeJS.
Front End - Angular 14x
socket io version - "socket.io-client": "^4.5.4",
BackEnd - Nodejs 14x
socket.io version - "socket.io": "^4.5.4",
FrontEnd Code -
import SocketClient from 'socket.io-client';
export class Customer_FileUpload implements OnInit {
#Input() io = SocketClient(environment.url, {
autoConnect: true
})
submitRequest() {
this.shared.submitRequest(data).subscribe({
next: (response) => {
const result = JSON.parse(JSON.stringify(response));
console.log(result);
this.io.emit('emit-data', "I am good");
this.io.on('data2', (msg) => {
console.log('message: ' + JSON.stringify(msg));
});
},
error: (error) => {
console.log(error);
}
})
}
}
Backend Code -
index.js
const express = require('express');
const bodyparser = require('body-parser');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const http = require('http');
const { RealTime } = require('./utils/socket');
const socket = new RealTime();
const app = express();
app.use(cors())
app.options('*', cors());
app.use(bodyparser.json({limit: '5mb', extended: true}))
app.use(bodyparser.urlencoded({limit: '5mb', extended: true}))
const authRoutes = require('./routes/authRoutes');
const apiRoutes = require('./routes/routes');
// For File Upload
app.use(fileUpload({
limits: { fileSize: 5 * 1024 * 1024 },
}));
app.use('/auth', authRoutes);
app.use('/user', apiRoutes);
//Capture All 404 errors
app.use(function (req,res,next){
res.status(404).send('Error - Unable to find the requested resource!');
});
app.use((req, res, next) => {
req.socket.on('error', () => {});
next();
});
const server = http.createServer(app);
socket.intialized_connection(server);
socket.init();
module.exports = server;
Socket.js
let io = null;
class RealTime {
constructor() {
if (io) return io;
io = this;
return io;
}
intialized_connection(httpServer) {
return (io = require('socket.io')(httpServer, {
cors: {
origin: '*',
// methods: ['GET', 'POST', 'PUT', 'DELETE'],
},
}));
}
init() {
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');
});
});
}
getIO() {
if (!io) {
throw new Error('Socket.io is not initialized');
}
return io;
}
sendEvents(event, data) {
this.getIO().emit(event, data);
}
receivedEvents(event) {
console.log(event);
this.getIO().on(event, function(data) {
console.log("I am emiiting here, ")
console.log(data)
});
}
}
module.exports = {
RealTime
};
Controller.js
exports.submitRequest = async(req, res) => {
socket.receivedEvents('emit-data');
socket.sendEvents("data2", {
message: "hello from nodejs controller"
});
res.json("done");
}
I have 2 issues here. Issues are ---
socket.receivedEvents -- Is not working, Not getting any error message, Neither in the client side not server side.
socket.sendEvents, It is working fine, in the client side, when we click second time. Attach the screenshot below.
First Time when we click on the submit button --
First time when we click on the submit
Second Time when we click on the submit button --
Second time when we click on the submit
Third Time when we click on the submit button --
Getting 2 times the same result.
Third time when we click on the submit
Any idea what I am doing wrong?
Can you please give me these 2 solution's problem?
So first I would like to say that I have looked at many other answers that were given for similar questions, but none worked for me.
My setup is a node js server and a react js client. And I am having trouble doing just a basic setup. Any one who would help me out here, I really appreaciate.
And also on the client code I have alternated through different options for serverUrl from localhost with the http http://localhost:6000 and without localhost:6000. Same for ip address.
NODE JS Server Code
const express = require('express');
const app = express();
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const project = require("./routes/api/project");
const auth = require("./routes/api/auth");
const email = require("./routes/api/email");
app.use(express.static(__dirname + '/public'));
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket)=> {
console.log("user connected")
socket.on('SEND_MESSAGE', function(data){
console.log("message received")
io.emit('RECEIVE_MESSAGE', data);
})
});
//*** Start of Routes ***//
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:6000");
res.setHeader("Access-Control-Allow-Credentials", "true");
next();
})
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/auth", auth);
app.use("/api/project", project);
app.use("/api/email", email);
//*** End of Routes ***//
const port = 6000;
server.listen(port, () => {
console.log(`Server Running at ${port}`);
});
REACT JS Client Code
import React,{useEffect,useState,useRef} from 'react';
import io from "socket.io-client";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
username: 'name',
message: 'hello world',
messages: []
};
this.serverUrl = '127.0.0.1:6000';
this.socket = io(this.serverUrl, {reconnect: true});
this.setupSocket();
}
setupSocket() {
this.socket.on('connection', (data) => {
console.log(`Connected: ${data}`);
});
}
render(){
return(<p>Hello<p>)
}
}
export default App
It may have a problem with your socket server you can change your port and check if it is working
I'm trying to learn socket.io in my Angular/Node app.
I would emit an event in angular side then listen to it in Back end.
In my component file :
import { MatTableDataSource } from '#angular/material';
import { AjouttextService } from '../ajouttext.service';
import { DataSource } from "#angular/cdk/collections";
import { Observable } from "rxjs/Observable";
import { nomchamp } from '../model';
import * as io from "socket.io-client";
#Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
constructor(private dataService: AjouttextService) { }
data = [];
url = 'http://localhost:8080';
private socket = io.connect(this.url);
displayedColumns = ['text'];
dataSource = new UserDataSource(this.dataService);
;
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
}
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
}
Emit event in Angular is set OnInit so it should emit an event in all cases and my component is called by app.component.
Then In server side I would print a console.log on 'save-message' event
var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes");
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
...Config...
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
app.use("/v1", routerProj, function (req) {
//Create HTTP server and listen on port 8000 for requests
});
// Print URL for accessing server
console.log("Server running at http://127.0.0.1:8080/");
io.on("connection", function (socket) {
console.log("user connected !");
});
io.on('save-message', function (socket) {
console.log("user saved message");
});
When I run server only connection event is working. I get " user connected in my console but not " user saved message"
What I expect ?
Print user saved message on server console when client run app ( DatatableComponent component )
try to modify your server side code to:
io.on('connection', function (socket) {
console.log('user connected !');
socket.on('save-message', function (socket) {
console.log('user saved message');
});
});
Register message listener on socket object instead of io which is received upon initial connection.