Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

sockets - Emitting a message in sails v0.11 (client-side)

I'm having some issues with the newest version of sails.js (0.11.0). It stated in github that plain socket.io code will be accepted and ran in sails.js; however, I am simply trying to emit a message from a client when they click on something like so:

$('#myBtn').on('click', function(){
     io.socket.emit('message', {  
         message: {
             subject: subject
         },
         sender: id
     });  

});

I end up getting an "Uncaught TypeError: undefined is not a function" on the line of io.socket.emit() aka emit is not a function of io.socket.

Here are some references that I have looked at:

I have a feeling with the updated version of sails, instead of emitting a message I should be doing something along the lines of:

io.socket.post('/user/message', data, function(data, jwres) {

});

Something concerns me with the following answer here:

It states "class rooms" are being deprecated along with publishCreate, publishDestroy, introduce, and obituary.

So do I follow a Pub/Sub paradigm, re-write my more "socket-io-ish" code to utilize sails Blueprints & Pub/Sub, or continue in my socket-io fashion?

Is there another way of emitting a message from client using sails?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are correct in that the recommended way of communicating with the server via sockets is to use the RESTful socket client methods. The benefit is that you can use the regular Sails routing and controller/action architecture for socket communication instead of having to support a whole other layer of subscription and event-handling on the backend. This is one of the main reasons why @mikermcneil originally created Sails. Two things to note:

  1. You can use req.isSocket in your controller action to determine whether the request is coming from a socket, and
  2. You can get the raw, underlying socket.io instance on the client with io.socket._raw, which will have the emit method. But again, this is not the recommended practice.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...