標籤:
以前就一直想在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 實現推送