First, the front and back end common communication method
1. Ajax
The browser initiates the request, the server returns the data, the server cannot actively return the data, the real-time data interaction can only be Ajax polling (let the browser send a request in a few seconds, and then update the client display. This approach actually wastes a lot of traffic and creates a lot of pressure on the service side.
2. WebSocket
WebSocket is HTML5 out of the Thing (protocol), is a full-duplex communication mechanism, the two ends can be in a timely manner to each other, the data, mutual communication, only the browser and the server to establish a connection, the server can actively push the data to the browser to implement real-time data updates.
Native WebSocket support to IE11, the actual development, there are more famous two libraries Socket.io (English, Chinese version may be new and not in time) and SOCKJS, they are the original API has been further encapsulated and compatible with IE, provides more features, are divided into the client and the service side of the implementation, in practical applications, you can choose to use.
WebSocket implementation requires a backend to build a websocket server, but if you want to build a websocket server is not so easy, because WebSocket is a new communication protocol, is still a draft, does not become a standard, There is no mature websocket server or library implementation of WebSocket protocol, we have to write code to parse and assemble websocket packets. To complete a WebSocket server, it is estimated that all people want to give up, fortunately, there are several relatively good open source libraries in the market for us to use, such as Pywebsocket,websocket-node, libwebsockets and so on, These library files have already implemented the encapsulation and parsing of websocket packets, and we can call these interfaces, which greatly reduces our workload.
Second, about Socket.io
The goal of Socket.io design is to support any browser, any mobile device. Currently supports mainstream PC browser (Ie,safari,chrome,firefox,opera, etc.), mobile browser (iphone Safari/ipad safari/android Webkit/webos WebKit, etc.). Socket.io is based on node. JS and simplifies the WebSocket API, unifying the communication APIs. It supports: WebSocket, Flash sockets, Ajax long-polling, Ajax multipart streaming, Forever IFrame, JSONP polling. Socket.io solves real-time communication problems, and unifies the client and server programming. After you start the socket, it's like building a client-to-server pipeline with both sides.
Third, the use of websocket in Socket.io
1. Service-side
Io.on (' Connection ', function (socket));//Listener Client connection, callback function will pass this connection socket
Io.sockets.emit (' String ', data);//broadcast messages to all clients
Io.sockets.socket (Socketid). Emit (' String ', data);//Send a message to the specified client
Socket.on (' String ', function (data));//Listen for information sent by the client
Socket.emit (' String ', data);//Send a message to the client of the socket
Broadcast messages
Broadcast Message Socket.broadcast.emit ("MSG", {data: "Hello,everyone"}) to clients other than yourself Broadcast Message Io.sockets.emit ("MSG", {data: "Hello,all"}) to all clients;
Group
Socket.on (' group1 ', function (data) { socket.join (' group1 ');}); Socket.on (' Group2 ', function (data) { Socket.join (' group2 '); });
Client sends
Socket.emit (' group1 '), you can join the group1 group;
Socket.emit (' group2 '), you can join the GROUP2 group;
Multiple groupings can exist for a client (subscription mode)
Kicking out a group
Socket.leave (Data.room);
Send a message to a user in a group
Do not include your own socket.broadcast.to (' group1 '). Emit (' event_name ', data); including own io.sockets.in (' group1 '). Emit (' event_name ', data);
The broadcast method allows the current socket client not to be within the group
Gets the connected client socket
Io.sockets.clients (). ForEach (socket) { //...})
Get group Information
Get all Room (group) information io.sockets.manager.rooms//To get the room information entered by this Socketid io.sockets.manager.roomclients[socket.id]// Get the client in the particular room and return all socket instances in this Chamber io.sockets.clients (' particular rooms ')
Another way to group
Io.of ('/some '). On (' Connection ', function (socket) { socket.on (' test '), function (data) { Socket.broadcast.emit (' Event_Name ', {}); }) ;
Client
var socket = io.connect (' ws://103.31.201.154:5555/some ') socket.on (' Even_name ', function (data) { Console.log ( data);})
Clients are linked to ws://103.31.201.154:5555 but the server can filter them out via Io.of ('/some ').
In addition, Socket.io offers 4 configurations of API:io.configure, Io.set, Io.enable, io.disable. Where Io.set is set for a single item, io.enable and io.disable are used for single-set Boolean configurations. Io.configure allows you to configure different parameters for different production environments, such as devlopment,test, and so on.
2. Client
Create a socket connection
var socket = io ("ws://103.31.201.154:5555");
Listening for service messages
Socket.on (' msg ', function (data) { socket.emit (' msg ', {rp: "Fine,thank You"});//Send message to Server console.log (data);});
Socket.on ("String", Function (data)) listens to the message sent by the server sting parameter is the same as the first parameter of the service-side emit
Monitor socket disconnect and re-connect.
Socket.on (' Disconnect ', function () { Console.log ("Break with Service");}); Socket.on (' Reconnect ', function () { Console.log ("Reconnect to Server");});
Client Socket.on () Listener event: Connect: Connection Successful connecting: Connecting disconnect: Disconnecting connect_failed: Connection failure Error: Error occurred and cannot be handled by other event types mess Age: Same server-side message event anything: Same server-side anything event reconnect_failed: Reconnection Failure Reconnect: Successfully reconnect reconnecting: reconnecting when first connected, Event firing Order is:connecting->connect; when the connection is lost, the event firing order is: disconnect->reconnecting (multiple possible)->connecting-> Reconnect->connect.
The front and back end common communication way--Ajax, WebSocket