支持多房间,支持私聊,使用nowjs库,服务器端代码不到100行。需要jquery1.7.1和coffee-script.js,读者可自行下载。
重点:
1、nowjs中Group的使用,如何遍历Group内的users。
2、客户端如何异步调用服务器端函数。
3、如何与特定用户通信。
运行
[quote]node app.js[/quote]
在浏览器中访问[url]http://localhost:8080[/url]
app.js
require('coffee-script');
require('./chatroomserver');
chatroomserver.coffee
coffeescript代码,重点部分已加上注释
fs = require 'fs'
url = require 'url'
html = fs.readFileSync __dirname + '/chatroom.html'
jquery = fs.readFileSync __dirname + '/../js/jquery-1.7.1.min.js'
coffeescript = fs.readFileSync __dirname + '/../js/coffee-script.js'
server = require('http').createServer((req, res)->
pathname = url.parse(req.url).pathname
res.end html if pathname == '/'
res.end jquery if pathname == '/jquery.js'
res.end coffeescript if pathname == '/coffee-script.js'
)
server.listen 8080
nowjs = require 'now'
everyone = nowjs.initialize server
rooms = {}
rooms['lobby'] = '大厅'
rooms['room1'] = '房间1'
rooms['room2'] = '房间2'
rooms['room3'] = '房间3'
onlineUsers = {} #所有在线用户
everyone.now.chckUser = (name, callback) -> #重点,使用异步方法调用
callback onlineUsers[name] != undefined #检查是否已有同名用户
everyone.now.initlize = ->
@now.updateRooms rooms
@now.room = 'lobby'
onlineUsers[@now.username] = @user.clientId
_lobby = nowjs.getGroup @now.room
_lobby.addUser @user.clientId
_lobby.now.receiveMessage "[SYS]#{@now.username} 进入#{rooms[@now.room]}, 欢迎!"
updateRoomUser @now.room
updateRoomUser = (roomid) ->#更新房间的用户
_users = []
_group = nowjs.getGroup roomid
_group.getUsers (usersid) ->#用Group#getUsers(callback)方法
_users = []
_users.push _group['users'][userid]['now']['username'] for userid in usersid #重点:取group中的用户名,要注意group的结构
_group.now.updateOnlineUsers _users
everyone.now.changeRoom = (newRoom) ->
nowjs.getGroup(@now.room).removeUser(@user.clientId)
nowjs.getGroup(@now.room).now.receiveMessage "[SYS]#{@now.username}离开#{rooms[@now.room]}进入#{rooms[newRoom]},再见!"
updateRoomUser @now.room
nowjs.getGroup(newRoom).addUser(@user.clientId)
@now.room = newRoom
nowjs.getGroup(newRoom).now.receiveMessage "[SYS]#{@now.username} 进入#{rooms[newRoom]},欢迎!"
updateRoomUser newRoom
everyone.disconnected ->#当断开连接时,触发
nowjs.getGroup(@now.room).now.receiveMessage "[SYS]#{@now.username}走了,再见!"
nowjs.getGroup(@now.room).removeUser(@user.clientId)
delete onlineUsers[@now.username]
updateRoomUser @now.room
everyone.now.distributePersonalMessage = (to, message) -> #私聊
self = @ #保存this
_gruop = nowjs.getGroup(@now.room)
_gruop.hasClient onlineUsers[to], (bool) -> #判断用户是否在线,使用回调函数
if bool
self.now.receiveMessage "我对#{to}说:#{message}"
nowjs.getClient onlineUsers[to], ->
this.now.receiveMessage "#{self.now.username}对我说:#{message}"#重点:如何跟特定用户通信
else
self.now.receiveMessage "[ERR]#{to}不在这个房间!"
everyone.now.distributeMessage = (message) ->
nowjs.getGroup(@now.room).now.receiveMessage(message);
chatroom.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>聊天室</title>
</head>
<script type="text/javascript" src="/jquery.js"></script>
<script src="/nowjs/now.js"></script>
<script src="/coffee-script.js"></script>
<script type="text/coffeescript">
now.receiveMessage = (message) ->
$("div#talkFrame").append "<br>"+ message
$(document).ready ->
$('#login').click ->
if $('#userName').val() == ''
alert 'please input user name!'
else
now.chckUser $('#userName').val(), (exist)-> #重点:使用回调函数,异步调用的方式。
if exist
alert '该用户已存在,请另取名字!'
$('#userName').focus()
else
now.username = $('#userName').val()
now.initlize()
$('span#name').text("#{now.username}说:")
$("#prePage").hide()
$("#mainPage").show()
$(document).on "click", "a.change", ->#点击房间名时进入房间。jquery对于动态创建元素的访问方式,此方式需要jquery1.7.+版本
now.changeRoom($(this).attr('id'))
$('#currentName')[0].innerHTML = $(this).text()
$(document).on "click", "a.users", -> #点击用户名时
$("input#message").val("@#{$(this).text()}:")
$("input#message").focus()
$(document).on "keydown", "input#message", (event)->#捕获回车
if event.keyCode==13
$('input#send').click()
else
$('input#send').click() if event.altKey and event.keyCode==83#Alt + s快捷键发送
$('input#send').click ->
mess = $('input#message').val()
if mess == ''
return
#head = "#{now.username} 说:"
if mess[0] == '@' #私聊
if mess.search(':') == -1
alert '格式不对,对象名后面少了":",请重新输入!'
$("input#message").focus()
return
to = mess.substring 1, mess.search(':')#提取私聊对象
head = "#{now.username} 对 #{to} 说:"
now.distributePersonalMessage to, utils.toStaticHTML mess.substring mess.search(':') + 1
$('input#message').val "@#{to}: "
else
now.distributeMessage "<a href='#' class='users'>#{now.username}</a> 说:#{utils.toStaticHTML mess}"
$('input#message').val ''
now.updateRooms = (rooms) ->
$('div#rooms').empty()
$('div#rooms').append "<a href='#' id = #{roomid} class='change'>#{rooms[roomid]}</a> " for roomid in Object.keys rooms
now.updateOnlineUsers = (users) ->
$('div#onlineUsers').empty()
$('div#onlineUsers').append "<br/><a href='#' class='users'>#{user}</a>" for user in users
utils = toStaticHTML: (text)->
inputHtml = text.toString()
inputHtml.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
</script>
<body>
<div id='prePage' class='page' style='width:690px;text-align:center;'>
<input id='userName' type='text' placeholder="请输入您的昵称"/>
<input id='login' type='button' value='进入聊天室'/>
</div>
<div id='mainPage' class='page' style='display:none;'>
<div style='overflow:hidden;'>
<div class='talkLeft'>
<h2 id='currentName' style='text-align:center;'>大厅</h2>
<div id='talkFrame'></div>
<div id='inputDiv'>
<span id ="name"></span><input type="text" placeholder="嗨,随便说点啥呗" id="message" size="20"></textarea>
</div>
<div>
<input class='f-right' type='button' value='发送' id="send"/>
</div>
</div>
<div class='talkRight'>
<div id='onlineUsers'></div>
</div>
<div id = 'rooms' style='text-align:center;'>
</div>
</div>
</div>
</body>
</html>
网页有部分借鉴https://github.com/auzll/nodechat。
附加信息,有兴趣的读者可以自己尝试:
Group有Group#hasClient = function (clientId, callback)判断用户是否在组里,但是没类似Now#getClient = function (clientId, callback)。Group#getClient应该很有用,能不能自己加上去呢?找到now\lib\gruop.js文件,添加下面的代码:
Group.prototype.getClient = function (clientId, callback) {
callback.apply(this.users[clientId]);
};
于是服务端私聊部分的代码可写成:
everyone.now.distributePersonalMessage = (to, message) -> #私聊
self = @ #保存this
_gruop = nowjs.getGroup(@now.room)
_gruop.hasClient onlineUsers[to], (bool) -> #判断用户是否在线,使用回调函数
if bool
self.now.receiveMessage "我对#{to}说:#{message}"
_gruop.getClient onlineUsers[to], ->
this.now.receiveMessage "#{self.now.username}对我说:#{message}"#重点:如何跟特定用户通信
else
self.now.receiveMessage "[ERR]#{to}不在这个房间!"