ASP.NET MVC 結合NODEJS 實現推送

來源:互聯網
上載者:User

標籤:

以前就一直想在Web上做個即時通訊的功能,直到最近才有時間,NodeJs確實是不錯的選擇。

在這裡就不考慮美觀的問題了,簡單的輸入推送訊息,保證用戶端能接收到推送訊息,

 

服務端,簡單代碼,參考如下:

//引入http模組var Http = require(‘http‘);//連接埠號碼var Port = process.env.port || 1337;//引入express模組var Express = require(‘express‘),    App = Express(),    Server = Http.createServer(App),    Io = require(‘socket.io‘).listen(Server); //引入socket.io模組 並綁定到伺服器Server.listen(Port);//輸出服務啟動console.log(‘server started‘);//當前線上人數  var onlineCount = 0;var messages = [];//socket 部分Io.on(‘connection‘, function (socket) {    //疊加當前線上人數      onlineCount++;      console.log(‘目前使用者數量:‘ + onlineCount);    //用戶端中斷連線      socket.on(‘disconnect‘, function () {        if (onlineCount > 0) {            //當前線上使用者減一              onlineCount--;            console.log(‘目前使用者數量:‘ + onlineCount);        }    });    // 從用戶端接收資料    socket.on(‘fromWebClient‘,        function(webClientData) {            console.log(webClientData);            messages.push(webClientData);            socket.broadcast.emit(‘pushToWebClient‘, { hello: webClientData });        });    //推送用戶端        //socket.emit(‘pushToWebClient‘, { hello: ‘world‘ });    messages.forEach(function(msg) {        socket.send(msg);    });});

  

用戶端,簡單代碼參考:

1 var socket = io.connect(‘192.168.1.23:1337‘);2 $(function () {3  //從伺服器接受資料4     socket.on(‘pushToWebClient‘, function (data) {5         alert(data.hello);6     });7 });
View Code

 

推送方,如下:

$("#btnSend")            .click(function () {                var msg = $("#sendMsg").val();                var socket = io.connect(‘127.0.0.1:1337‘);                socket.emit(‘fromWebClient‘, msg);            });

 

ASP.NET MVC 結合NODEJS 實現推送

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.