Speaking of socket. Io, you have to talk about websocket first.
Websocket is a protocol based on stateless HTTP. To understand it literally, TCP socket is applied to HTTP, so that both parties can establish a connection channel in active state andFull Duplex(Two devices communicate with each other simultaneously ).
Unlike Ajax, It is not request-oriented and response-oriented, but can be directly transmitted through the send method. Websocket can be said to be a subset of socket. Io. There are actually five underlying implementations of socket. Io, and websocket is only one of them. By default, the underlying layer of the socket. Io connection is also an instance that calls websocket. When I/O. when connect () establishes a socket connection, it returns a namespace instance, and another socket instance in the namespace instance. When a connection is created or a message is sent, namespace-> socket-> transport-> websocket (xhrpolling ...), in fact, the real sender of a message is the underlying websocket, xhrpolling, or other types, while the socket. i/O is just an organizer. When we need to establish a connection, It will select a connection method internally and then implement the connection.
Websocket working method:
- Server: Initialize the server, bind websocket. Io to the server, listen to the event, and send the message to the client.
- Client: Initialize websocket and establish a connection with the server to send information.
Comparison of socket. Io and websocket:
- Socket. io message transmission is based on transmission, but not all rely on websocket. It supports a large number of browsers and devices, including IE6 and iOS. websocket belongs to the HTML5 category, earlier browsers were not supported.
- Socket. Io provides a reliable event mechanism that listens to connect and disconnect events rather than open and close events.
- When the socket. Io connection is lost, it is automatically reconnected by default. websocket usually needs to refresh the browser.
- Socket. Io allows you to transmit simple text information like websocket, and distribute JSON data through emit and listen events.
- Socket. Io supports using namespaces in a single connection to differentiate messages.
- Socket. Io can be easily broadcast without the need to define the broadcast mechanism.
Working Method of socket. IO:The main functions of socket. Io are emit and on.
- Socket. emit submits (sends) an event, the event name can be customized, there are some default events (connection, message, disconnect), followed by an object, indicates the content sent to the socket.
- Socket. On receives an event, followed by the callback function called by the event, where data is the received data.
- Built-in default event names such as Io. the on function accepts "connection" as the client-initiated connection event. After the connection is successful, the callback function with the socket parameter is called. "Disconnect" indicates that the client is disconnected, "Message" indicates receiving a message. The Custom Event name should not be the same as the default event name built in socket. Io to avoid unnecessary trouble.
- Server: bind socket. Io to the common HTTP. server,
var app = require(‘express‘)();var server = require(‘http‘).Server(app);var io = require(‘socket.io‘)(server);server.listen(80);
Set listener
io.on(‘connection‘, function (socket) { socket.emit(‘news‘, { hello: ‘world‘ }); socket.on(‘my other event‘, function (data) { console.log(data); });});
- Client: When socket. Io is bound to HTTP. server, the URL starting with/socket. Io is automatically blocked and redirected. Socket. Io. JS is actually placed in the node_modules folder on the server side. You can also copy this file to a local file to make it a JS file of the client, so that you do not need to request to the node server every time to enhance stability.
<script src="/socket.io/socket.io.js"></script><script> var socket = io(); // TIP: io() with no args does auto-discovery socket.on(‘connect‘, function () { // TIP: you can avoid listening on `connect` and listen on events directly too! socket.emit(‘ferret‘, ‘tobi‘, function (data) { console.log(data); // data will be ‘woot‘ }); });</script>
Common APIs:
Send messages to all clients:io.emit
// The following two will emit to all the sockets connected to '/' Io. sockets. emit ('hi', 'everone'); // v0.9, V1.0 also supports Io. emit ('hi', 'everone'); // short form. We recommend that you use this
Enter a room, send messages to the room (you can also receive messages), and leave the room: Socket. Join, Io. To, socket. Leave
Io. on ('connection', function (socket) {socket. join ('some room'); Io. to ('some room '). emit ('some event'): // In achieves the same effect as to, Io. in (). emit ();
Socket. Leave ('some room ');});
Broadcast messages to a room (messages cannot be received by yourself ):Socket. Broadcast. To ('some room '). emit ('message'); change room to ID
Io. on ('connection', function (socket) {socket. on ('Say to someone', function (ID, MSG) {socket. broadcast. to (ID ). emit ('My message', MSG); // The ID is socket # ID });});
Used as websocket: (client)socket.send(‘hi‘)
, For (server)socket.on(‘message‘, function(data){})
.
References: http://socket.io/docs/
Http://raytaylorlin.com/Tech/web/Nodejs/socket-io-tutorial/
Http://blog.csdn.net/jiangcs520/article/details/17287531