node. JS's Socket.io module

Source: Internet
Author: User

The Socket.io module is a node. JS-based project that works primarily to apply the WebSocket protocol to all browsers. The module is mainly used in real-time long-connected multi-request projects, such as online games, real-time chat, real-time stock view, QR code scan login and so on. --node.js Development Real-combat detailed

The installation and configuration methods are consistent with the General NPM module installation configuration:

#    NPM Install Soctet.io

It should be because my local server is the Win7 operating system, so there will be a lot of error when installing, but it does not seem to affect the use of Socket.io module, not too concerned about this. I don't know if this is the case on Linux, so I'll try it on my server sometime.

An example of an official Socket.io module is recommended here, which realizes the function of an online chat, which is helpful for learning this module.

Next, introduce the interfaces commonly used in Socket.io.

1.io.sockets.on (' Connection ', function (socket) {}): This interface is the Socket.on interface in Socketapi, which is a little different from the Socket.on interface below. Whenever a user connects, it executes the callback function once. Here are three points to note, Io.sockets.on is sockets, the event is sent with the name connection, and the callback function needs to pass in a parameter socket.

2.soctet.on (' event ', function () {}): This function is to execute the callback function after receiving the event. The first parameter is the event name, and the second parameter is the callback function to execute.

3.socket.emit (' event ', {test: ' Hello World '},function () {}): This interface is sending an event. The first parameter is the event name, the second parameter is the data content being sent, and the third parameter is the callback function that needs to be executed.

4.socket.broadcast.emit (' event ', function () {}): As with his interface name, it will be broadcast to users of other connected sites. But a little more puzzling, he will not be sent to the source, for example: A users connect to the Web site will send a connection event to the server, the server received after the use of this interface broadcast to all connected users a notification event, then User B, User C ... Can receive this notification event, and user A will not receive it.

5.socket.send (' Hello '): The first parameter is the data sent, similar to emit, is used to send data, but if sent with send, can not specify the event name, received by the message event to receive, and emit can define the event name to receive data. Therefore, emit is usually used, and send is not recommended.

6.socket.get/set (' foo ', bar, function () {}): The first parameter is the data name, the second parameter is the data being sent, the third is the callback function, the set is used to save the data, and get is used to fetch the saved data.

Finally put on my own test code:

Server

varApp = require ('Express')();varHTTP = require ('http'). Server (app);varIO = require ('Socket.io') (HTTP), app.Get('/', Function (req, res) {Res.sendfile (__dirname+'/index.html');}); Io.on ('Connection', function (socket) {Console.log ('a user connected'); Socket.broadcast.emit ('Hi'); Socket.on ('Chat Message', Function (msg) {Io.emit ('Chat Message', MSG);  }); Socket.on ('Disconnect', function () {Console.log ('User Disconnected'); });}); Io.emit ('some event', { for:'everyone'}); Http.listen ( the, function () {Console.log ('listening on *:3000');});

Client

<!doctype html>"Https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.js"></script> <script src="Http://code.jquery.com/jquery-1.11.1.js"></script> <style> * {margin:0; Padding0; box-sizing:border-box;}      Body {font:13px Helvetica, Arial;} form {background: # the; padding:3px; Positionfixed; Bottom0; Width -%; } Form Input {border:0; padding:10px; Width -%; Margin-right:.5%; } Form button {width:9%; Background:rgb ( the,224,255); Border:none; padding:10px; } #messages {List-style-type:none; Margin0; Padding0; }      #messages li {padding:5px 10px;} #messages Li:nth-Child (odd) {background: #eee;} </style> "Messages"></ul> <form action=""> <input id="m"Autocomplete="off"/><button>send</button> </form> </body> <script>varSocket =io (); $('form'). Submit (function () {Socket.emit ('Chat Message', $('#m'). Val ()); $('#m'). Val ("'); return false;      }); Socket.on ('Chat Message', Function (msg) {$ ('#messages'). Append ($ ('<li>'). Text (msg));      }); Socket.on ('Hi', Function (msg) {Console.log ('Hi');    }); </script>

node. JS's Socket.io module

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.