Web real-time communication Socket.io compatible browser version Ie7&ie8&ie9&ie10__javascript

Source: Internet
Author: User
Tags emit sendfile

Because of browser compatibility issues, not all environments can use websocket this better way. That is, depending on the browser or the environment, the client and the server may need to use different modes of communication. Socket.io Introduction

In order to solve the above problem, Socket.io appeared.

Socket.io is a nodejs, a software package for real-time communication (both client-side and server-side), and Socket.io is fully implemented by JavaScript.

The goal of Socket.io design is to support any browser, any device. In the interface, Socket.io unified the communication API, in the internal implementation of support Websocket,ajax long-polling, AJAX multipart streaming, Forever iframe and other methods. In other words, Socket.io will choose the appropriate communication method according to the environment.

In the Socket.io, there are namespace and room concepts, you can easily group socket, easy to implement some such as chat room applications.

For more Socket.io related content, please refer to the link.

Okay, it's the chat program again, this time it's Socket.io version. Implement

On the implementation side, the client uses Socket.io directly, and the server uses Nodejs. Client

The client first creates a socket object that listens for "new_message" and "User_status" events.

var socket;

     function Initsocket () {socket = IO ("http://" + location.host);

     Socket.emit ("Add_client", $ ("#clientNameSpan"). Text ());
         Socket.on ("New_message", function (data) {Console.log (data);
         data = eval ("(+ Data +)"); if (Data.sender = = $ ("#clientNameSpan"). Text ()) {$ ("#inbox"). Append ("<div class= ' Chatitems ' ><span cl ass= ' msg msend ' ><span class= ' sender ' > "+data.sender+": </span> "+data.msg+" </span></div>
         "); else {$ ("#inbox"). Append ("<div class= ' chatitemr ' ><span class= ' msg mrecv ' ><span CLA
         ss= ' sender ' > "+data.sender+": </span> "+data.msg+" </span></div> ");
     $ ("#inbox"). ScrollTop ($ ("#inbox") [0].scrollheight);

     });
         Socket.on ("User_status", function (data) {$ ("#clientCount"). Text ("Online User:" +data.length);
         $ ("#clients"). Children (). remove (); for (var i = 0; i<data.length; I+ +) {$ ("#clients"). Append ("<span id= ' client ' >" +data[i]["clientname"]+ "</span>")}} )
 }
Service Side

For the service side, the first is some static files, page processing.

Get the static files
app.get ("/", Function (req, res) {
    res.sendfile (__dirname + "/index.html");
});

App.get ("/static/jquery-1.11.3.js", Function (req, res) {
    res.sendfile (__dirname + "/static/jquery-1.11.3.js");
});

app.get ("/static/json2.js", Function (req, res) {
    res.sendfile (__dirname + "/static/json2.js");
});

App.get ("/static/style.css", Function (req, res) {
    res.sendfile (__dirname + "/static/style.css");
});

In addition, the main function of the server is to receive the message, and then broadcast the message.

The server logs all users according to the socket ID and user name, and is stored in an array. Whenever a user joins or the user exits, the server sends the user array to the client via the "User_status" event, so that the client can display the current number of users.

//Save all the client {"Sid": Socket.id, "ClientName": client} var clients = [] Io.on ("Connecti

        On ", function (socket) {Socket.on (" add_client ", function (client) {Console.log (client+" jion the chat ");
        var clientobj = {};
        clientobj["sid"] = socket.id;

        clientobj["ClientName"] = client;
        Clients.push (Clientobj);

    Io.emit ("User_status", Clients)});
        Socket.on ("New_message", Function (msg) {Console.log ("Server got message:" +msg);
        Console.log ("Send Message using:" +socket.conn.transport.name);
    Io.emit ("New_message", msg);

    }); Socket.on ("Disconnect", function () {for (var i = 0; i<clients.length; i++) {if (clients[i]["sid"] = =
                Socket.id) {Console.log (clients[i]["ClientName"]+ "leave the chat");
                Clients.splice (i, 1);
            Break
    } io.emit ("User_status", clients);

}); });
Run effect

The first is a login page that binds the user name to the socket ID on the server for simple user statistics.

The console side prints the messages received by the server, as well as the user's join/leave situation.

When the user status changes, the page receives a "User_status" event and then updates the user status bar.
Socket.io compatibility Test

The advantage of the Socket.io is that it unifies the interface, shields the user from the bottom, and can support different devices and choose the best way to communicate.

The following on the compatibility of Socket.io some simple test, mainly to see ie7-10.

First, note the following section of the server's code that shows how the current message is communicated:

Console.log ("Send Message using:" +socket.conn.transport.name);
IE10

I installed this machine is IE10, through the server console can be seen, in IE10 Socket.io will choose "WebSocket" as the final mode of communication.
IE9/IE8

Open IE, enter the following page via F12, then set to IE9.

Through the test can see, Socket.io in IE9 can work, because IE9 does not support "WebSocket", so Socket.io finally chose "Polling" as the final means of communication.

Switch to IE8 mode through the above settings, because IE8 does not support "WebSocket", so Socket.io will switch the communication mode to "Polling". IE7

Using the same steps to test, Socket.io works in the polling mode in IE7.

The only problem encountered in IE7 is that the "json.stringify" method is not supported, so the IE7 is hack in the following way:

<!--[if IE 7]>
    <script src= "/static/json2.js" ></script>
<![ Endif]-->
Summary

As can be seen from the example, after using Socket.io, we only need to understand the API provided by Socket.io, without needing to be concerned about which communication method to use, it is simple and convenient to use.

The article on the compatibility of Socket.io on IE to do some simple test, the results are still very satisfied with the WebSocket environment, Socket.io automatically switched to the polling way, users do not care about the difference in the environment.

Socket.io as a cross environment, a variety of connections to automatically switch the tool to further simplify the development of Web real-time communication applications.

Ps: The source code for example can be downloaded from here.

Socket.io Introduction
Implementing
Client
Server
Run effect
Socket.io compatibility test
IE10
IE9/IE8
IE7
Summary
Author: Tian Subtotal
Source: http://www.cnblogs.com/wilber2013/
This article copyright to the author and blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious position to give the original connection, Otherwise, the right to pursue legal liability is retained.
If you feel good, please click on the recommendation and attention.

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.