Nik Hendricks
Nik Hendricks

Reputation: 294

Using callback function in websocket api javascript

i have a websocket client using the websocket api for javascript and my server is using socket.io

I'm trying to put a callback function like this

client js Using build in javascript WebSocket api


//im formatting the string like that because thats what socket.io needs for some reason

  var sendString = '42' + JSON.stringify(['checkLogin' , username, password])
    socket.send(sendString, function(returnData){
      console.log(returnData);
      resolve(returnData);
    })

but I keep getting an error that callback is not a function on my server-side using socket.io which looks like this

server js using socket.io library


socket.on('checkLogin', function(username, password, callback){
  console.log(username, password)
  webUser.findOne({username:username}, function(err, docs) {
    console.log(docs)
    if(docs){
      if(docs.password == password){
        callback(docs._id)
      }else{
        callback(false)
      }
    }
    if(!docs){
      callback(false)
    }
  });
})

what can i change to make this set the callback function correctly

Upvotes: 0

Views: 2271

Answers (1)

jfriend00
jfriend00

Reputation: 707836

First problem. If you're using socket.io on the server-side, you must be using a socket.io client. You can't use a webSocket client with a socket.io server. They won't connection. This is true even though socket.io is using the webSocket transport underneath. A socket.io server needs the socket.io layer on top of webSocket.

Second problem, to send data with a socket.io client, you would use either socket.send() when you are just sending raw data with no message name or you would use socket.emit() when you are sending a message name.

In your case, I would recommend you use this on the client:

 socket.emit('checkLogin', {username, password}, function(result => {
     console.log(result);
 });

And, then modify your server code like this:

socket.on('checkLogin', function(data, callback){
  let username = data.username;
  let password = data.password;
  console.log(username, password)
  webUser.findOne({username:username}, function(err, docs) {
    console.log(docs)
    if(docs){
      if(docs.password == password){
        callback(docs._id)
      }else{
        callback(false)
      }
    }
    if(!docs){
      callback(false)
    }
  });
})

Upvotes: 1

Related Questions