Preliminary study on Socket.io

Source: Internet
Author: User
Tags emit

Establishing the server
//server.js
varIO = require (' Socket.io ') (80);varChat =io. of ('/chat ')//Set namespace. On (' Connection ',function(socket) {Socket.emit (' A message ', {// this will only be sent to its own socket that:' Only ' , '/chat ': ' would get ' }); Chat.emit (' A message ', {// global send everyone:' In ' , '/chat ': ' would get ' }); });varNews =io. of ('/news '). On (' Connection ',function(socket) {Socket.emit (' Item ', {news: ' Item ' }); });
<script>  var chat = io.connect (' http://localhost/chat ')  // /chat/news Here is the namespace, It doesn't matter    with the URL . = Io.connect (' http://localhost/news ');//can also be directly IO (), which will connect Chat.on based on your current URL    ( function () {    chat.emit (' hi! ' );  });    News.on (function  () {    news.emit (' woot ');  }); </script>
Send Receipts
Server.js
var io = require (' Socket.io '),io.on (function (socket) { Socket.on ( function (name, fn) { fn (' woot '); });});

Client.js

<script>  var//  Tip:io () with no args does auto-discovery  function // tip:you can avoid listening on ' connect ' and listen on events directly too!    function (data) {   ///emit function The third optional parameter is a callback function, which can have parameters, the call of the parameter is determined      by the server //  data Will is ' Woot '    })  ; </script>
Set the Sending object
// Send yourself socket.broadcase.emit ()  // Send to users outside of themselves Io.emit ()  // Send all Users io.of ()/io.to ()/  / users sending namespaces/rooms

Preliminary study on Socket.io

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.