Server-side Building reference Socket IO website, which has a very detailed description, follow the steps down, and finally can be simulated chat on localhost.
The following is a description of the client.
- Introduction of Socket.io.js:
<script src= "Js/socket.io.js" ></script>
<!--Chats Tab-- <ion-tab title= "Chats" icon-off= "Ion-ios-chatboxes-outline" icon-on= " Ion-ios-chatboxes "href=" #/tab/chats "> <ion-nav-view name=" Tab-chats "></ion-nav-view> </ion-tab>
<ion-view view-title= "Chats" ><ion-content overflow-scroll= "true" style= "Overflow:hidden" >< Ion-scroll zooming= "true" direction= "y" style= "height:500px;" > <ion-list> <uib-alert ng-repeat = "Msginfo in Messages" Type= "{{msginfo.type}}" close= "Closealert ($index)" >{{msginfo.msgtype}}: {{msginfo.msg}} </uib-alert> </ion-list></ion-scroll> <div class= "Bar Bar-footer" > <label class= "Item Item-input" style= "width:85%" > <input type= "text" placeholder= "Add your message here" Ng-model= "MSG" ></input> </label> <button class= "button button-positive" ng-click= "Send ( msg) ">Send</button> </div> </ion-content> </ion-view>
- Define the state of chats in App.js:
. State (' Tab.chats ', { URL: '/chats ', views : { ' tab-chats ': { templateurl: ' templates/tab-chats.html ', controller: ' Chatsctrl '}} })
. Controller (' Chatsctrl ', function ($scope, mediaPlayer, chats) { $scope. messages = []; Chats.on (' Chat message ', function (msg) { var msginfo = {msg:msg, type: ' Warning ', Msgtype: ' Receiver '} $scope. Me Ssages.push (msginfo); Console.log (' Receive msg from others: ' + msg '); }); $scope. Send = function (msg) { var msginfo = {msg:msg, type: ' Success ', Msgtype: ' Sender '} $scope. Messages.push (msginfo); Console.log (' Start to send msg: ' + msg); Chats.emit (' Chat message ', msg); }; $scope. Closealert = function (index) { $scope. Messages.splice (index, 1); };})
var baseUrl = ' http://localhost:3000/';. Factory (' chats ', function socket ($rootScope) { var socket = Io.connect (BASEURL); return { on:function (EventName, callback) { Socket.on (eventName, function () { var args = arguments; $rootScope. $apply (function () { callback.apply (socket, args);});} , emit:function ( EventName, data, callback) { socket.emit (eventName, data, function () { var args = arguments; $rootScope. $apply (function () { if (callback) { callback.apply (socket, args);}}) } };})
Resources:
https://github.com/jbavari/ionic-socket.io-redis-chathttp://jbavari.github.io/blog/2014/06/17/ building-a-chat-client-with-ionic/http://socket.io/get-started/chat/
13th: Realizing instant communication based on Socket.io