Sockets are used for real-time communication between the browser and the server. In the past, regular polling was often used to simulate real-time communication, but this undoubtedly increased the pressure on the server.
Here are some uses of the collected Socket.io:
Service-Side Section
Io.on (' connection ',function(socket)); // listen to the client connection, the callback function will pass the connection socket io.sockets.emit (' String ', data); // broadcast messages to all clients Io.sockets.socket (Socketid). Emit (' String ', data); // sends 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
Send Message
// broadcast messages to clients other than themselves Socket.broadcast.emit ("msg", {data: "Hello,everyone"// broadcast messages to all clients) io.sockets.emit ("msg", {data: "Hello,all"});
Group and group send messages
function (data) { socket.join (' group1 ');}); Socket.emit (' group1 ')//join group1 Group;// Remove Group socket.leave (data.room); // Group send messages-do not include your own socket.broadcast.to (' group1 '). Emit (' Event_Name ', data); // groups send messages-including their own io.sockets. inch (' group1 '). Emit (' Event_Name ', data)
Client
//Create a socket connectionvarSocket = IO ("WS://103.31.201.154:5555 ");//Listening for service messagesSocket.on (' Msg ',function(data) {Socket.emit (' msg ', {rp: "Fine,thank You"});//send a message to the serverconsole.log (data);}); Socket.on ("String",function(data))//the message sent by the Listener server sting parameter is the same as the service-side emit first parameter//Monitor socket Disconnect and re-connect. Socket.on (' Disconnect ',function() {Console.log ("Disconnected from service");});
Project Code section:
The functions used in the project are very simple, the most important thing is to enter the room, exit the room, and then send the information of these functions.
varIO = require (' Socket.io ')();varXssescape = require (' Xss-escape '));varUserList = [];//User List//var currentroom = []//is used to hold the collection of the current connected user in which room;Io.on (' Connection ',function(socket) {//Listen for connection events and listen to the following four events at the same timejoinroom (socket); Disconnect (socket); Say (socket); Close (socket);});//Enter the roomfunctionJoinroom (socket) {Socket.on (' Joinroom ',function(userInfo) {socket.join (userinfo.roomid);//adds the currently connected user to the socket in the specified Roomid roomSocket.userinfo = UserInfo;//Add a user attribute to this socketUserlist[socket.id] = UserInfo;//in the list of users, the current user's information is stored because the socket is uniqueSocket.emit (' UserList ', getusernamelist (socket));//returns the user list to the current room to (socket.userInfo.roomId).Socket.broadcast.to (socket.userInfo.roomId). Emit (' Userjoin ', {userId:userInfo.userId, nickName:userInfo.nickName, socketId:socket.id }); //notify other users that someone has entered the roomSocket.emit (' ServerMessage ', ' welcome into the room! ‘);//send a welcome message to the user when the room has been successfully entered. Socket.emit ("Test", "test"); })}//get a list of current room usersfunctiongetusernamelist (socket) {varNameList = [];//List of users holding the current room varUsersinroom = Io.sockets.adapter.rooms[socket.userinfo.roomid];//get information about a given room for(varSocketidinchUsersinroom.sockets) {//Socketid for all online users in a given room if(userlist[socketid]!=NULL) {//The information for the corresponding connected user is stored in the array and returned. Namelist.push ({userid:userlist[socketid].userid, Nickname:userlist[socke Tid].nickname, Socketid:socketid}); //Pass User ID nickname Sockedid } } returnNameList;}//exit the roomfunctionClose (socket) {Socket.on (' Close ',function() {socket.leave (socket.id);//leave the roomSocket.broadcast.to (socket.userInfo.roomId). Emit (' Userleave ', {//like this room in the user sends the user to leave the notice, the foreground will delete this user in the current user listuserId:socket.userInfo.userId, NickName:socket.userInfo.nickName, Socketid:socket . ID}); Removenickname (socket.id); //remove this person from the user list collection })}//Close PagefunctionDisconnect (socket) {Socket.on (' Disconnect ',function() {//when a page is closed between users, the logic that executes is the same as leaving the roomSocket.leave (socket.id); if(Socket.userinfo! =NULL) {socket.broadcast.to (socket.userInfo.roomId). Emit (' Userleave ', {userId:socket.userInfo.userId, nickName:socket.userInfo.nickName, S OcketId:socket.id}); Removenickname (socket.id); } });}//Send Messagefunctionsay (socket) {Socket.on (' Say ',function(message) {//broadcast messages, when the current station sends a message, it takes a current room ID, and then broadcasts the message directly to other users in the room. Content =Message.content.trim (); Roomid=Message.roomid; Socket.broadcast.to (Roomid). Emit (' Usersay ', {title:socket.userInfo.nickName, Msg:xssescape (content)});//broadcast messages require xssescape (content) in case a script attack occurs });}//Delete a user in a roomfunctionRemovenickname (socketid) {DeleteUserlist[socketid];} Exports.listen=function(_server) {returnIo.listen (_server);};
Implementation of socket service side