Socket. Io Overview

Source: Internet
Author: User
Tags emit http cookie

In order to prevent crawlers from crawling articles on unscrupulous websites, we hereby mark and repost the source of the article. Laplacedemon/sjq.

Http://www.cnblogs.com/shijiaqi1066/p/3826251.html

 

 

 

Socket. Io

Socket. Io is used for real-time communication between the browser and node. js. Socket. Io is designed to support any browser and any mobile device. Supports mainstream PC browsers (ie, Safari, chrome, Firefox, opera, etc.) and mobile browsers (iPhone Safari/iPad Safari/Android WebKit/WebOS WebKit ).

Socket. Io supports the following communication methods. Based on the degree of browser support, you can automatically select which technology to use for communication:

  • Websocket
  • Flash socket
  • Ajax long-polling
  • Ajax multipart streaming
  • Forever IFRAME
  • Jsonp polling

Socket. Io solves the real-time communication problem and unifies the programming methods between the server and the client. After the socket is started, it is like creating a pipeline between the client and the server. The two sides can communicate with each other.

 

About engine. Io

Engine. Io is an abstract Implementation of socket. Io, which serves as the transmission layer for data exchange between the socket. Io server and the browser. It does not replace socket. Io. It just abstracts inherent complexity and supports real-time data exchange between multiple browsers, devices, and networks.

 

 

 

Basic use of socket. Io to create a server

For example, there are two simple methods to create an I/O server.

VaR IO = require ('socket. Io ') (); // or var Server = require ('socket. Io'); var IO = new server ();

 

 

 

Server Configuration

The configuration items of the socket. Io server are the same as those of engine. Io.

  • Pingtimeout (number): the waiting time for the response packet, in milliseconds. The default value is 60000.
  • Pinginterval (number): Set to send a ping packet at a certain time, which can be used to set the heartbeat packet. The default value is 25000.
  • Maxhttpbuffersize (number): Maximum Message Size, which can be used to prevent DoS attacks. The default value is 10e7.
  • Allowrequest (function): This configuration item is a function. The first parameter is a handshake or connection request. The second parameter is a callback function (ERR, success). Success is a Boolean value. False indicates a connection failure. Err indicates an error code. This function can be used to determine whether to continue.
  • Transports (<array> string): Specifies the transmission connection mode. The default value is ['polling', 'websocket '].
  • Allowupgrades (Boolean): indicates whether the transfer protocol can be upgraded. The default value is true.
  • Cookie (string | Boolean): the name of the HTTP cookie. The default value is Io.

 

Use SOCKET. Io through node HTTP Server

// Server (app.js)var app = require(‘http‘).createServer(handler)var io = require(‘Socket.IO‘)(app);var fs = require(‘fs‘);app.listen(80);
function handler (req, res) { fs.readFile(__dirname + ‘/index.html‘, function (err, data) { if (err) { res.writeHead(500); return res.end(‘Error loading index.html‘); }
res.writeHead(200); res.end(data); });}io.on(‘connection‘, function (socket) { socket.emit(‘news‘, { hello: ‘world‘ }); socket.on(‘my other event‘, function (data) { console.log(data); });});// Client (index.html)<script src="/Socket.IO/Socket.IO.js"></script><script> var socket = io(‘http://localhost‘); socket.on(‘news‘, function (data) { console.log(data); socket.emit(‘my other event‘, { my: ‘data‘ }); });</script>

 

 

 

Use SOCKET. Io through express 3/4

// Server (app.js)var app = require(‘express‘)();var server = require(‘http‘).Server(app);var io = require(‘Socket.IO‘)(server);server.listen(80);app.get(‘/‘, function (req, res) {  res.sendfile(__dirname + ‘/index.html‘);});io.on(‘connection‘, function (socket) {  socket.emit(‘news‘, { hello: ‘world‘ });  socket.on(‘my other event‘, function (data) {    console.log(data);  });});// Client (index.html)<script src="/Socket.IO/Socket.IO.js"></script><script>  var socket = io.connect(‘http://localhost‘);  socket.on(‘news‘, function (data) {    console.log(data);    socket.emit(‘my other event‘, { my: ‘data‘ });  });</script>

 

 

 

 

 

Send and receive events

Socket. Io provides default events (such as connect, message, and disconnect ). In addition, socket. Io allows sending and receiving custom events.

Event sending:

// Send it to the corresponding client socket. emit ('message', "this is a test"); // send it to all client Io. sockets. emit ('message', "this is a test"); // send a message to the client specified by socketid. Io. sockets. socket (socketid ). emit ('message', 'for your eyes only'); // send a Custom Event socket. emit ("My-Event", "this is a test ");

 

 

Event receipt:

Socket. On ("event name", function (data) {// data is the received data .});

 

 

 

Sample Code

Example 1:

// note, io.listen(<port>) will create a http server for youvar io = require(‘Socket.IO‘).listen(80);io.sockets.on(‘connection‘, function (socket) {  io.sockets.emit(‘this‘, { will: ‘be received by everyone‘});  socket.on(‘private message‘, function (from, msg) {    console.log(‘I received a private message by ‘, from, ‘ saying ‘, msg);  });  socket.on(‘disconnect‘, function () {    io.sockets.emit(‘user disconnected‘);  });});

 

 

 

Example 2:

// Server (app.js)var io = require(‘Socket.IO‘).listen(80);io.sockets.on(‘connection‘, function (socket) {  socket.on(‘ferret‘, function (name, fn) {    fn(‘woot‘);  });});// Client (index.html)<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>

 

 

 

 

Broadcast messages

A broadcast message is sent by the server and sent to all clients except the currently connected clients.

// Send the message to all clients except the sender. Socket. Broadcast. emit ('message', "this is a test ");

 

 

For example, broadcast user-defined events.

var io = require(‘Socket.IO‘).listen(80);
io.sockets.on(‘connection‘, function (socket) { socket.broadcast.emit(‘user connected‘);});

 

 

 

Send volatile data

Volatile means that when the server sends data, the client cannot normally receive the data for various reasons, such as network problems or being in the connection establishment phase of a persistent connection. In this case, our application will become suffer, so we need to consider sending volatile data.

var io = require(‘Socket.IO‘).listen(80);io.sockets.on(‘connection‘, function (socket) {  var tweets = setInterval(function () {    getBieberTweet(function (tweet) {      socket.volatile.emit(‘bieber tweet‘, tweet);    });  }, 100);  socket.on(‘disconnect‘, function () {    clearInterval(tweets);  });});

 

Even if the client is not connected, the server can send data in this way, and the server will automatically discard the failed data.

 

 

Namespace

You can set a subroutine for socket. Io through the namespace. The default namespace is "/", and socket. Io connects to this path by default.

You can use the of () function to customize the namespace.

// Server (app.js)var io = require(‘Socket.IO‘).listen(80);var chat = io  .of(‘/chat‘)  .on(‘connection‘, function (socket) {    socket.emit(‘a message‘, {        that: ‘only‘      , ‘/chat‘: ‘will get‘    });    chat.emit(‘a message‘, {        everyone: ‘in‘      , ‘/chat‘: ‘will get‘    });  });var news = io  .of(‘/news‘)  .on(‘connection‘, function (socket) {    socket.emit(‘item‘, { news: ‘item‘ });  });// Client (index.html)<script>  var chat = io.connect(‘http://localhost/chat‘)    , news = io.connect(‘http://localhost/news‘);  chat.on(‘connect‘, function () {    chat.emit(‘hi!‘);  });  news.on(‘news‘, function () {    news.emit(‘woot‘);  });</script>

 

 

 

 

Room

The room is a very useful function provided by socket. Io. The room is equivalent to providing a namespace for some specified clients. All broadcasts and communication in the room will not affect clients outside the room.

 

Enter and exit the room

Use the join () method to add the socket to the room:

io.on(‘connection‘, function(socket){  socket.join(‘some room‘);});

 

Use leave () to exit the room:

socket.leave(‘some room‘);

 

Send messages in the room

Send a message in a room:

io.to(‘some room‘).emit(‘some event‘);

 

The to () method is used to send messages to other sockets except the current socket in the specified room.

socket.broadcast.to(‘game‘).emit(‘message‘,‘nice game‘);

 

The IN () method is used to send messages to all sockets in the specified room.

io.sockets.in(‘game‘).emit(‘message‘,‘cool game‘);

 

 

When the socket enters a room, you can broadcast messages in the room in the following two ways:

// Broadcast an event to my room. The submitter will be excluded (that is, no message will be received) Io. sockets. on ('connection', function (socket) {// note: In comparison with the following, the event socket is submitted from the client perspective. broadcast. to ('My room '). emit ('event _ name', data);} // broadcast an event to the another room. All clients in the room will receive a message. // note: In comparison with the above, here we will submit the event IO from the server perspective. sockets. in ('another room '). emit ('event _ name', data); // broadcast Io to all clients. sockets. emit ('event _ name', data );

 

In addition to broadcasting messages to a room, you can use the following APIs to obtain room information.

// Obtain information about all rooms // The key is the room name, and the value is the socket ID array Io corresponding to the room name. sockets. manager. rooms // obtain the client in the participant room and return all socket instance IO in the room. sockets. clients ('particle room') // use socket. ID to obtain the information of the socket room I/O. sockets. manager. roomclients [socket. id]

 

 

 

 

 

 

 

For more API information, see the official socket. Io documentation. In addition, many materials on the network are based on version 0.9, which is quite different from the current version 1.0. Please read carefully: migration from 0.9

 

 

Other materials:

Http://www.csser.com/board/4f5ed68d417a7f6a6e000059

Http://raytaylorlin.com/Tech/web/Nodejs/socket-io-tutorial/

Http://raytaylorlin.com/Tech/web/Node.js/socket-io-advanced/

 

 

 

 

In order to prevent crawlers from crawling articles on unscrupulous websites, we hereby mark and repost the source of the article. Laplacedemon/sjq.

Http://www.cnblogs.com/shijiaqi1066/p/3826251.html

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.