Real-time communication of node. JS closest Combat (11)

Source: Internet
Author: User
Tags emit sendmsg sqlite database hasownproperty sessionstorage

Once in the faint secretly repeatedly in the cross-examine, just know light leisurely is true, listen to the song, write blog, feel came.

Today we mainly look at Socket.io real-time communication, first look at the interface.

.row .col-md-9  .panel.panel-primary   .panel-heading     H3.panel-title (style= ' font-size:13px; ')  chat message   .panel-body#div_msgbody (style= ' Min-height:590px;max-height:590px;o verflow:auto;max-width:750px; ')      #div_msg. Panel-content (style= ' word-wrap:break-word;word-break: break-word; ')    .panel-footer     #div_footer (style= ' height:36px;line-height:36px ')           .row      .col-md-8 (style= ' color : #3f51b5; Font-weight:bold ')  chat history:        input#chat_ history      .col-md-4.right-align-text         a#link_clear (href= ' javascript:void (0) ')  clear  .row   .col-md-10     input#txt_msg.form-control (type= ' text '  stYle= ' Height:40px;resize:none '  maxlength=200 placeholder= ' input message here. ')    .col-md-2.right-align-text    button#btn_send.k-button.k-primary (type= ' Button '  style= ' height:40px;width:100% ')      span.glyphicon.glyphicon-send      span (style= ' margin-left:5px ')  send .col-md-3  .panel.panel-primary    .panel-heading    h3.panel-title (style= ' font-size:13px; ')  members   .panel-body.panel-inner-height (style= ' Overflow:auto; ')      #div_users. Panel-content (style= ' word-break: break-word; ')    .panel-footer    .left-margin-10       Span.text-color#total member count:0#chat_historywindow (style= ' Display:none ')    #chat_ Historycontent.panel-content (style= ' word-wrap:break-word;word-break: break-word; ') Span#notifYblock scripts script (type= ' text/javascript '  src= '/javascripts/local/other/chat.js ') 

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/84/07/wKioL1eDsL6xz1MqAABsQWR8_7I057.png "title=" Qq20160711224356.png "alt=" Wkiol1edsl6xz1mqaabsqwr8_7i057.png "/>

This is the chat interface, the left is the chat content, the right is to participate in chat users. To implement this chat, we previously mentioned singalr in our blog, which can be used for asp.net,winform as well as WPF. Today we're going to use Socket.IO.js on the node. JS platform. The first thing to do is to refer to this extension package in your project.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/84/08/wKiom1eDscyQdWxlAACfiVxC6a8872.png "title=" Qq20160711224828.png "alt=" Wkiom1edscyqdwxlaacfivxc6a8872.png "/>

Once installed, the package is automatically added to the Package.json and managed.

"Dependencies": {     "Array-splice":  "^0.1.1",     " Body-parser ": " ~1.8.4 ",    " busboy ": " ^0.2.12 ",    " Cassandra-driver ": " ^3.0.0 ",    " Cookie-parser ": " ~1.3.3 ",      "Debug":  "~2.0.0",     "Express":  "~4.9.8",     " Express-session ": " 1.12.1 ",    " Gridfs-stream ": " ^1.1.1 ",      "Jade":  "^1.11.0",     "Log4js":  "^0.6.29",     " Mongoose ": " ~4.2.3 ",    " Morgan ": " ^1.6.1 ",    " request ":   "^2.67.0",     "Serve-favicon":  "~2.1.3",     "Socket.io":   "^1.3.7",     "String.prototype.endswith":  "^0.2.0",     " String.prototype.startswith ": " ^0.2.0 "  }

I also use the old version here, haha, OK, the old version of the new version can be used. We entered the theme, in the first environment, I said that our launch portal is www file.

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/84/07/wKioL1eDspryvKkZAAAOS6Gho1U804.png "title=" Qq20160711225157.png "alt=" Wkiol1edspryvkkzaaaos6gho1u804.png "/>

In the www file, we initialized some of Socketio's stuff.

Var chatusercount = 0;var chatusers = {};var server = app.listen ( App.get (' Port '),  function ()  {    debug (' express server listening  on port  '  + server.address (). port);}); Var io = require (' Socket.io ') (server); Io.on (' Connection ', function  (socket)  {     socket.on (' Joinchat ', function  (obj)  {     Console.log (' a user connected: ' +obj. UserName);         socket.name = obj. username;        if  (!chatusers.hasownproperty (obj. UserName))  {            chatusers[obj. username] = obj;             Chatusercount++;        }io.emit (' Joinchat ', &nbsp { chatusers: chatusers ,chatusercount: chatusercount,joineduser: obj});     });         socket.on (' Leftchat ',  function   ()  {            console.log (' a  User left ');            if  ( Chatusers.hasownproperty (socket.name))  {                 var obj = chatUsers[socket.name];                 delete chatUsers[socket.name];                  chatusercount--;                         io.emit (' Leftchat ',  { chatusers: chatusers, chatusercount: chatusercount, leftuser:  obj });            }         });     socket.on (' Disconnect ', function  ()  {          if  (Chatusers.hasownproperty (socket.name))  {             var obj = chatusers[ socket.name];            delete chatusers[ socket.name];            chatusercount--;             io.emit (' Leftchat ',  { chatUsers:  chatusers, chatusercount: chatusercount, leftuser: obj });         }    });     socket.on (' Message ', function  (obj)  {         io.emit (' message ',  obj);     });     socket.on (' Error ',  function (Exception)  {console.log (' Socket error '); Socket.destroy ( );     });

Here, when a client enters a chat, the Joinchat event is emitted and the Joinchat event is triggered in the background. When a connection is established between the client and the server, the server launches the broadcast joinchat, and all connected clients receive the broadcast, silently refreshing the interface. When the client user loses the connection (close the browser), the Disconnect event is automatically emitted, the server triggers the disconnect event, and the result is broadcast to each client, and the client automatically refreshes the page. When the user unload the page, Leftchat is triggered. When the client sends a message, a message event is triggered to send the user's messages to someone else. This is the process of the chat interface, very simple.

Next, let's look at the client code.

var popupnotification = $ ("#notify"). Kendonotification ({    autohideafter:  2000,    height: 60,    stacking:  "Down"}). Data (" Kendonotification "); Var socket = io (); Var loginuser = sessionstorage.getitem (" Loginuser ");if  (loginuser == null)  {  window.location.href = "/";   return;} Var userobj = eval ("("  + loginUser +  ")");     Sessionstorage.removeitem (' Chatuser '); Socket.emit ("Joinchat",  userobj); Socket.on (' Joinchat ',  function  (data)  {    if  (!sessionstorage.getitem (' Chatuser '))  {         sessionstorage.setitem (' Chatuser ',  json.stringify ({  "user") :  [] }));     }        var usersobj  = json.parSE (Sessionstorage.getitem (' Chatuser '));    if  (UsersObj.user.indexOf ( Data.joinedUser.UserID)  == -1)  {         UsersObj.user.push (Data.joinedUser.UserID);         Sessionstorage.setitem (' Chatuser ',  json.stringify (usersobj));         setchartdetail (data);                 if  (Data.joineduser.userid != userobj.userid)  {             popupnotification.show (' <span style= ' color:red > '  + data.joinedUser.FullName +  '  joined in.</span> ',  ' info ');         }    }); Socket.on (' Leftchat ',  function   (data)  {    var usersobj = json. Parse (Sessionstorage.getitem (' Chatuser '));    var index =  UsersObj.user.indexOf (Data.leftUser.UserID);         UsersObj.user.splice (index, 1);     sessionstorage.setitem (' Chatuser ',  Json.stringify (Usersobj));     setchartdetail (data);     Popupnotification.show (' <span style= ' color:red > '  + data.leftUser.FullName +  '  left.</span> ',  ' warning ');});

When the user enters this page, we launch the Joinchat and send the current logged-in user information to the server, and the server will broadcast the user information and the total number of calculated users to each client. Note here we to remind users, the use of kendonotification, the effect is as follows, when someone enters or leaves, there will be a popup prompt.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/84/08/wKiom1eDuAvCnttIAABY1yPLRUA192.png "title=" Qq20160711231504.png "alt=" Wkiom1eduavcnttiaaby1yplrua192.png "/>

When the user leaves, as above, when the user enters, the following

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/84/07/wKioL1eDuDbi3mmiAABxPpJdZlM722.png "title=" Qq20160711231553.png "alt=" Wkiol1edudbi3mmiaabxppjdzlm722.png "/>

OK, let's take a look at the main part, chat.

$ ("#btn_send"). Click (function () {sendmsg ();})    $ ("#txt_msg"). KeyDown (function (e) {if (E.keycode = =) {sendmsg ();    }}); function sendmsg () {var msg = $.trim ($ ("#txt_msg"). Val ());        if (msg) {var msgobj = {user:userobj, msg:msg};    Socket.emit ("message", msgobj); } $ ("#txt_msg"). Val ("");}

Above is the code to send the message by clicking the Send button or the text box, which is broadcast to the client by the background message.

Socket.on (' message ', function  (data)  {    var msgObj = data;         var userAvatar =  '/images/userlogin.png ';         if  (Msgobj.user.username == userobj.username)  {         $ ("#div_msg"). Append ("<div class= ' Row-margin ' >"          +  " '          +   "<span class= ' triangle ' ></span> '          +  ' <div  class= ' article '  style= ' word ' >  + msgObj.msg          +  "</div></div></div>");                 db.transaction (function  (TX)  {             tx.executesql (' Insert into chatrecords (UserId, senduserid,fullname,content)  values ("'  + userObj.UserID +  '", "'  +  msgobj.user.userid +  ' "," '  + msgObj.user.FullName +  ' "," '  + msgobj.msg  +  ') ');         });    }     else {        $ ("#div_msg"). Append ("<div  class= ' Row-margin ' > ' &NBSP;&NBSP;&NBSP;&NBsp;     +  "          +  ' <span style= ' left:10px;position:relative ' > '  + msgObj.user.FullName +  ' </span > "         + " <div class= ' Demo clearfix ' > "         + " <span class= ' triangle ' ></span> "         + " <div class= ' article ' > " +  msgobj.msg         +  "</div></div></div>") ;                 Db.transaction (function  (TX)  {             tx.executesql (' insert&Nbsp;into chatrecords (userid,senduserid,fullname,content)  values ("'  + userObj.UserID  +  ' "," '  + msgObj.user.UserID +  ' "," '  + msgObj.user.FullName +  ' ", "'  + msgObj.msg +  ') ');         });     }        var objDiv =  document.getElementById ("Div_msgbody");    objdiv.scrolltop =  Objdiv.scrollheight;});

In fact, this is just a process of spelling a message, if the sender is himself, then the message is displayed on the right, otherwise, the left display. Look at the chat between James and Lilei.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/84/07/wKioL1eDvFLChW-nAAEI2Pjo2wY690.png "title=" Qq20160711233320.png "alt=" Wkiol1edvflchw-naaei2pjo2wy690.png "/>

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/84/07/wKioL1eDvISxYZWoAAEF5YOxGPs308.png "title=" Qq20160711233411.png "alt=" Wkiol1edvisxyzwoaaef5yoxgps308.png "/>

See, chat is very happy. OK, the above people are not see a similar SQL code, good, is to save chat information to the local Websql SQLite database.

Db.transaction (Function (TX) {tx.executesql (' INSERT into Chatrecords (userid,senduserid,fullname,content) VALUE        S ("' + Userobj.userid + '", "' + MsgObj.user.UserID + '", "' + MsgObj.user.FullName + '", "' + msgobj.msg + '"); });

Before using it, we need to first connect to the database to create the table.

var db = OpenDatabase (' chathistory ', ' 2.0 ', ' Chat Records ', ten * 1024x768 * 1024x768);d b.transaction (function (TX) {Tx.execute SQL (' CREATE TABLE IF ' EXISTS chatrecords (id INTEGER PRIMARY KEY autoincrement,userid TEXT not NULL DEFAULT "", Senduser Id text NOT NULL default ' ", fullname text NOT null default '", content text NOT NULL default "", Indate DATETIME default CUR Rent_timestamp);});

It's really a bit like sqlsever's syntax, let's take a look at the chat history stored in the local websql, Google Chrome, press F12

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/84/08/wKiom1eDvhOAWuv8AAFYusu4uNo881.png "title=" Qq20160711234039.png "alt=" Wkiom1edvhoawuv8aafyusu4uno881.png "/>

See, the chat record has been stored, because I am a machine, a browser Open two tab page, so here the chat record is two, one is the sender, one is the recipient. Note that there is also a table here, sqlite_sequence, our primary key ID is defined as self-increment, so this table stores the maximum value of our self-increment column (ID).

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/84/07/wKioL1eDvwDz8K2YAABqyhD4c2k819.png "title=" Qq20160711234449.png "alt=" Wkiol1edvwdz8k2yaabqyhd4c2k819.png "/>

The maximum is 54, which is equal to the maximum value in our table chatrecords.


OK, this article here to say goodbye to everyone, the next section we will talk about interceptors, LOG4JS, server automatic compilation refresh.

This article is from the "Technology Creation value" blog, please be sure to keep this source http://leelei.blog.51cto.com/856755/1825565

Real-time communication of node. JS closest Combat (11)

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.