Introduction to HTML5 WebSocket 3-Communication model SOCKET.IO_JAVASCRIPT skills

Source: Internet
Author: User
Tags emit node server learnboost

Why is Socket.io born? Please see the following text description.

Why do you need Socket.io?

Node.js provides an efficient server-side runtime environment, but because of the different browser-side support for HTML5, providing an excellent real-time user experience for all browsers, and providing programmers with a consistent client-server programming experience, Socket.io is born.

The goal of Socket.io design is to support any browser, any mobile device. Currently supports mainstream PC browsers (Ie,safari,chrome,firefox,opera, etc.), mobile browsers (iphone Safari/ipad safari/android Webkit/webos WebKit, etc.).

Socket.io is based on Node.js and simplifies the WebSocket API, unifying various communication APIs. It supports: WebSocket, Flash sockets, Ajax long-polling, Ajax multipart streaming, Forever IFrame, JSONP polling.

Socket.io solves the real-time communication problem, and unifies the server and client programming methods. After the socket has been started, it is like establishing a channel between the client and the server, which can be used on both sides.

Installation

execute on the command line: NPM install Socket.io can be installed.

Server-side programming model

Server-side programming, like normal servers, starts servers, provides services, and handles events.

For example, the following server.js:

var http = require (' http '), url = require (' URL '), FS = require (' FS '), server;
  Server = Http.createserver (function (req, res) {//your normal server code var path = Url.parse (Req.url). Pathname;
   Switch (path) {case '/': Res.writehead ({' Content-type ': ' text/html '}); Res.write ('  

Client programming model

Client programming is similar to the way it is handled, connecting servers, interacting information.

For example, the following index.html page:

<!doctype html>  

Attention matters

1. Start the server or give it to node, open the Command Line window, navigate to the Server.js folder, and enter node Server.js to start the server.

In the index.html above, note this line: <script src= "/socket.io/socket.io.js" ></script>. If you do not want to use a local Socket.io script, you can

To directly use the following publicly available script:

<script src= "Http://cdn.socket.io/stable/socket.io.js" ></script>

Also note this line:socket = Io.connect (null).

Here the null represents the connection to the local service, can be replaced by "localhost", the effect is the same.

2. You can use Socket.io to start the HTTP service directly.

For example:

var io = require (' Socket.io '). Listen
Io.sockets.on (' Connection ', function (socket) {
 io.sockets.emit (' This ', {would: ' is received by everyone '});

3. Socket.io can send messages directly through the Send method, using the message event to receive messages, for example:

Server.js
var io = require (' Socket.io '). Listen
Io.sockets.on (' Connection ', function (socket) {
 socket.on (' message ', function () {});
};
index.html
<script>
 var socket = io.connect (' http://localhost/');
 Socket.on (' Connect ', function () {
  socket.send (' Hi ');
  Socket.on (' message ', function (msg) {
   //I msg
  }
); </script>

4. Send and process data

Both ends can be exchanged for events, data, and communication with each other. The code to send the event is: Socket.emit (action, data, function), where action is the name of the event, data is the date, function is the callback function, and the event code is: Socket.on (action, function), if the emit is sent with data, the parameter in the function contains the data. Socket.io in addition to sending and handling built-in events, such as Connect, disconnect, message. Also allows you to send and process custom events, such as:

Service side:

Io.sockets.on (' Connection ', function (socket) {
 socket.emit (' news ', {hello: ' world '});
 Socket.on (' My other event ', function (data) {
  console.log (data);}
);

Client:

<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 ', {i: ' data '}
); </script>

5. As you can see from the above, send and emit are available when sending the data. It's just that emit reinforces the handling of custom events.

6. The Get/set method of socket can be used on the server to store the relevant data of customer service end, for example:

Service side

var io = require (' Socket.io '). Listen
Io.sockets.on (' Connection ', function (socket) {
 Socket.on (' Set nickname ', function (name) {
  Socket.set (' Nickname ', name, function () {socket.emit (' ready ');});
 Socket.on (' msg ', function () {
  socket.get (' nickname ', function (err, name) {
   console.log (' Chat message by ', NA me);
  });

Client

<script>
 var socket = io.connect (' http://localhost ');
 Socket.on (' Connect ', function () {
  socket.emit (' Set nickname ', Confirm (' What is your nickname? ');
  Socket.on (' Ready ', function () {
   console.log (' Connected! ');
   Socket.emit (' msg ', confirm (' What are your message? ');
  }
); </script>

7. You can broadcast messages, such as in a chat room, to everyone except the current socket connection.

var io = require (' Socket.io '). Listen
Io.sockets.on (' Connection ', function (socket) {
 socket.broadcast.emit (' User connected ');
};

8. You can create multiple, independent channels in the same link, instead of creating multiple links. The official term is "multiple namespace," such as the official example:

var io = require (' Socket.io '). Listen
Server
var chat = io
 . of ('/chat ')
 . On (' Connection ', function (sockets) {
  socket.emit (' a message ', { That
    is: ' Only '
   , '/chat ': ' 'll get '
  };
  Chat.emit (' A message ', {
    everyone: ' In '
   , '/chat ': ' 'll Get '
  })
; var news = Io
 . of ('/news ')
 . On (' Connection ', function (socket) {
  socket.emit (' item ', {news: ' item '}); c18/>});
Client
<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>

Configuration of Socket.io

Socket.io's configuration is simple, and if you've configured Express, you'll find that they're almost in the same way. Let's look at a small example:

var io = require (' Socket.io '). Listen
Io.configure (' Production ', function () {
 io.enable (' Browser client ETag ');
 Io.set (' Log level ', 1);
 Io.set (' transports ', [
  ' WebSocket '
 , ' flashsocket ',
 ' htmlfile '
 , ' xhr-polling '
 , ' Jsonp-polling '
 ]);
Io.configure (' development ', function () {
 io.set (' transports ', [' websocket ']);

As you can see, Socket.io uses configure, set, enable, disable to configure.

1. Use the Configure method to configure behavior in different running environments, which means that different configuration options are enabled in different environments. The first parameter of configure is the running environment, and the second parameter is the function that is configured. The operating environment is typically like production or development, and of course there can be arbitrary strings. If the first parameter of the Configure is omitted, the following configuration is public, regardless of the circumstances, is valid.

2. Configure a variety of operating environment, then how to set the current running in that environment? This is done by modifying the value of the environment variable node_env on the command line.

3. In the Configure configuration function, we can use set, enable, disable set the relevant options.

4. The specific can configure the item reference: Https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
Practical reference

Socket.io Introduction: http://davidchambersdesign.com/getting-started-with-socket.io/

Socket.io installation and use instructions: http://socket.io/

Socket.io Wiki:https://github.com/learnboost/socket.io/wiki

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.