Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  8] [ 3]  / answers: 1 / hits: 15434  / 6 Years ago, mon, march 19, 2018, 12:00:00

I am developing a node app using express which has a chatting system and I am using socket.io but I get this error



Server is listening on 3000
made socket connection
C:UsersUserMyFolderProjectsFMISappapp.js:139
socket.on('chat', function(data){
^

TypeError: socket.on is not a function
at Namespace.<anonymous>
(C:UsersUserMyFolderProjectsFMISappapp.js:139:12)
at emitOne (events.js:116:13)
at Namespace.emit (events.js:211:7)
at Namespace.emit
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)


This what I have tried to do in my `app.js



var reload = require('reload');
var bodyParser = require('body-parser');
var app = express();
var socket = require('socket.io');
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.set('views','app/views');
app.locals.siteTitle = FMIS;
app.use(express.static('app/public'));

app.use(require('./routes/Chat_api'));
app.use(require('./routes/Chat'));

var server = app.listen(app.get('port'),()=>{
console.log('Server is listening on '+ app.get('port'));
});

var io = socket(server);

io.on('connection',function(){
console.log('made socket connection');
socket.on('chat', function(data){
// io.sockets.emit('chat',data);
console.log(data);
});
});
reload(server, app);


I send and recieve data from the client like this



 socket.emit('chat',{
user: chatUsername.value,
Message: chatMessage.value
});

socket.on('chat',function(data){
// showMessage(data);
console.log(data);
});

More From » node.js

 Answers
13

You're using the library reference for socket.io, which does not contain the function property on. What are you trying to do is use the socket provided to you as an argument of the callback on io.on connection event. To fix that you can just add socket to the arguments on your callback function. Like this:



io.on('connection',function(socket) {
console.log('made socket connection');
socket.on('chat', function(data){
// io.sockets.emit('chat',data);
console.log(data);
});
});


Now socket is referring to the socket provided to you by the connection. See this example for more info.


[#54913] Wednesday, March 14, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;