nodejs框架-thinkjs实现简单的聊天室功能,thinkjs内置了对websocket的支持,所以要实现聊天室的话非常简单。
Controller里代码
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
module.exports = Controller(function(){ //websocket列表 var wsList = {}; setInterval(function(){ for(var id in wsList){ wsList[id].send({ name: '机器人', text: '每隔10秒我就发一条消息哦' }) } }, 10000) return { indexAction: function(){ this.display(); }, /** * 建立连接 * @return {[type]} [description] */ openAction: function(){ var websocket = this.http.websocket; var id = websocket.id; for(var wid in wsList){ wsList[wid].send({ name: '系统', text: 'id_' + id + '进入了聊天室' }); } wsList[id] = websocket; this.http.on("websocket.close", function(){ console.log('close') delete wsList[id]; for(var wid in wsList){ wsList[wid].send({ name: 'id_' + id, text: 'goodbye~~' }); } }) }, /** * 获取到消息 * @return {[type]} [description] */ messageAction: function(){ var data = this.get(); data.name = 'id_' + this.http.websocket.id; data.wslength = Object.keys(wsList).length; //有消息后向所有人广播 for(var id in wsList){ wsList[id].send(data); } } } }) |
浏览器中的代码
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
$(function(){ var htmlMaps = { '<': '<', '>': '>', '"': '"e;', "'": ''' } var escape_html = function (str) { return (str + "").replace(/[<>'"]/g, function(a){ return htmlMaps[a]; }) } function getWebSocket(){ var socket = new WebSocket("ws://" + location.hostname + ":1234/test/websocket/open"); var deferred = $.Deferred(); // 打开Socket socket.onopen = function(event) { $('<div>连接成功,开始聊天吧 ^_^</div>').appendTo(dataList); deferred.resolve(socket); // 监听消息 socket.onmessage = function(event) { var data = JSON.parse(event.data).result; console.log(data); var html = '<div><span>'+data.name+'</span> ' html += '<span>' + escape_html(data.text) + '</span></div>' $(html).appendTo(dataList); dataList[0].scrollTop = 100000000; }; // 监听Socket的关闭 socket.onclose = function(event) { socket = null; console.log("websocket closed") }; }; return deferred; } var ws = getWebSocket(); var dataList = $('.data-list'); var input = $('#textField').select(); $('#submitBtn').click(function(){ var value = input.val().trim(); if (!value) { return input.focus(); }; ws.then(function(ws){ input.val('').focus(); ws.send(JSON.stringify({ jsonrpc: "2.0", method: "/test/websocket/message", params: {text: value}, id: 1 })) }) }) }) |