How to invoke server-side function from client-sid

2019-02-16 04:07发布

问题:

Using express framework. I want to invoke function init() { // } which resides in server.js (set up using express.js)

The client side includes code

<script src="/socket.io/socket.io.js"></script>
<script>
 var socket = io.connect('http://localhost');
</script>

But i want to invoke init() from <a href='WHAT TO PUT HERE'> Click to invoke Init() on server </a> on index.html on client side.

Edit:

<a href='javascript:callInit();'> Get Init </a>

calls the function callInit() above in

 <script> function callInit() {  socket.emit('init', 'data'); }

But `socket.emit('init', 'data'); does not execute. I can't understand why?

回答1:

Client.js

  <script src="/socket.io/socket.io.js"></script>
  <script>
     var socket = io.connect('http://localhost');
     $("#urAnchorTagId").click(function(){
         socket.emit('urEvent','urData');
   });
 </script>

Server.js

   var app = express();
   var server = http.createServer(app);
   var io = require('socket.io').listen(server);
   server.listen(8080);
   io.sockets.on('connection', function (socket) {
       socket.on('urEvent', function (data) {
        function init(){
             //ur task

            };
   });
 });


回答2:

If you want a 'generic" way to invoke method of server object, and get their results, easy pretty easy to do.

For example, I'd like to expose method of a given service object at server side:

var service = {
   init: function(p1, p2) {
     return p1+p2;
   }
};

// exposes all methods
for (method in service.__proto__) {
  // use a closure to avoid scope erasure
  (function(method){
    // method name will be the name of incoming message
    socket.on(method, function() {
      // assumption that the invoked method is synchronous
      var result = service[method].apply(service, arguments);
      // method name suffixed with '-resp' will be the outgoing message
      socket.emit(method+'-resp', result);
    });
  })(method)

At client side, you do something like:

socket.emit('init', 10, 5);
socket.on('init-resp', function(result) {
  console.log('addition result: '+result);
});

And it may print 15 on the console.

If you need asynchronous behaviour, I can provide another example.