Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...